Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass any array as a parameter in Java?

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.

like image 221
Alan Escreet Avatar asked Nov 23 '15 12:11

Alan Escreet


2 Answers

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.

like image 191
wero Avatar answered Sep 21 '22 08:09

wero


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.

like image 38
Jalai Avatar answered Sep 22 '22 08:09

Jalai