For example, for a single method that reads the elements of an array, how can the programmer allow either an array of objects or an array of primitives to be passed as the parameter? Object[] arrayName
will only accept an array of Objects, and generic variables do not accept primitives. Is there a way to accept either type of array without overloading the method?
views:
142answers:
6The only common supertype of Object[]
and (for example) int[]
is Object
. So the answer to your question is "No".
EDIT: Yes you could use Object
as the parameter type, but you'd need to jump through hoops (reflection or lots of typecasts) before you could use it. And you'd have to deal with the case that the thing that was passed was not an array at all.
The OP's goal is to find a single type that is better than overloading. IMO, using Object
as a claytons array type clearly does not meet this goal. It requires more complicated code, it less efficient and it is more vulnerable to unexpected runtime type errors.
You can pass an array of either type as an Object
.
From there, you have to use reflection. In particular isArray()
, getComponentType()
, and isPrimitive()
will tell the method what it has been passed. It's some of the unfortunate untidiness introduced by primitive data types.
In java, all the primitive types have object wrappers. eg. Integer
for int
, Boolean
for boolean
, etc. If you are willing to accept an array of object wrappers, then having your method accept Object[]
should work for you.
What is the context?
Your situation might be calling for generics, with which you could pass in Collection<Integer>
or Collection<SomeOtherType>
as you please.
class Test
{
public static void main(String[] args)
{
run(new String[] {"Hello", "World"});
Integer[] inputs = {1, 2, 3};
run(inputs);
//run(new int[] {1, 2, 3}); //this would not do!
}
private static void run(Object[] inputs)
{
for(Object input : inputs)
System.out.println(input);
}
}
It outputs : Hello World 1 2 3
So, even with auto-boxing, the array of Objects cannot take primitves because array itself is derived from Object. Hence my answer to the question is NO.
However, in C# you can have the magic "var" to go around this issue :)
A bit different approach, have you considered a combination of autoboxing and varargs? This however requires a change in the higher level, so instead of passing an int[] {1, 2, 3}
, you'll have to pass in 1, 2, 3
. Not sure if this matters.
public static void main(String... args) {
doStuff("one", "two", "three");
doStuff(1, 2, 3);
doStuff("one", 2, 3.3);
doStuff(new String[] {"one", "two", "three"});
doStuff(new Integer[] {1, 2, 3});
doStuff(new Object[] {"one", 2, 3.3});
}
public static void doStuff(Object... args) {
for (Object o : args) {
// ...
}
}