2

Possible Duplicate:
Can a single Java variable accept an array of either primitives or objects?

I want to create an method that accepts either an arbitrary array. The array can be an array of primitives, or an array of objects.

Unfortunately, I can't do

public void myMethod(Object[] a) {...}

because primitives aren't objects! Is there a way to abstract this one level further?

EDIT I understand that I can pass it as an Object, but then how do I access it as an array within the method? I can't do:

public void myMethod(Object[] a) {
     Object something = a[0];
     }
1

3 Answers 3

1

All array types are of type Object, nothing more sepecific.

import java.lang.reflect.Array;

public void myMethod(Object array) {
    Object first = Array.get(a, 0); // Object, primitives are wrapped.
}
Sign up to request clarification or add additional context in comments.

Comments

1
import java.lang.reflect.Array;

public void myMethod(Object[] a) 
{ 
    Array.get(a, 0);     
 }

1 Comment

you still cannot pass an int[] to an Object[]
0

Unfortunately, there is no better solution (at the moment) than overloading myMethod to handle each kind of primitive type you want to handle. You can for example see the signatures of the binarySearch methods in the class Arrays

Of course, you can also pass an Object and check if it is an array (and in this case, check the type of this array) using reflection. However, you're application will become less typesafe if you do so.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.