How can I write a method that will accept any array of any type (including primitives) as a parameter?
For instance, I would like both of the following calls to work:
int[] intArray = {1, 2, 3};
String[] strArray = {"1", "2"};
hasSize(intArray, 3);
hasSize(strArray, 2);
The closest I've gotten so far is:
public static <T> boolean hasSize(T[] array, int expectedSize)
{
return (array.length == expectedSize);
}
...but this doesn't work for primitives.
A primitive array and an object array don't share are base class except Object
.
So the only possibility would be to accept an object and inside the method check if it is an array
public static <T> boolean hasSize(Object x, int expectedSize)
{
return (x != null) && x.getClass().isArray() ?
java.lang.reflect.Array.getLength(x) == expectedSize :
false;
}
Of course this also accepts non-arrays, probably not the solution you want.
For this reason the JDK mostly provides identical methods for object arrays and primitive arrays.
If I recall correctly, you can't create a generic array that you expect to have take primitives, as the primitives themselves are not classes and not available to the Java generics system.
Rather, your incoming array would have to be an Integer[], Double[], etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With