How to pass any array as a parameter in Java?

How to write a method that will accept any array of any type (including primitives) as a parameter?

For example, 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 got so far:

 public static <T> boolean hasSize(T[] array, int expectedSize) { return (array.length == expectedSize); } 

... but this does not work for primitives.

+6
source share
4 answers

The simplest array and the array of objects do not share the base class, except for Object .

Thus, the only way would be to take an object and inside the method to 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, maybe not the solution you want.

For this reason, the JDK basically provides identical methods for arrays of objects and primitive arrays.

+5
source

If I remember correctly, you cannot create a shared array that you expect primitives to accept, since the primitives themselves are not classes and are not available for the Java generic system.

Rather, your incoming array should be Integer [], Double [], etc.

+1
source

You can do something like this

 public class A { public static void main (String[] args) { int[] intArray = {1, 2, 3}; String[] strArray = {"1", "2"}; hasSize(Arrays.asList(intArray), 3); hasSize(Arrays.asList(strArray), 2); } public static <T> boolean hasSize(List<T> array, int expectedSize) { return (array.size() == expectedSize); } } 

This is not exactly what you want. But you can take advantage of the universal mechanism by passing a list of arrays, and autoboxing will do the job for you.

If this approach is good for you, then good, but if this is not a good approach, unfortunately, the general mechanism does not support primitive types, so you need to override the method for each type of array.

0
source

As mentioned above, you cannot mix a primitive array and an array of objects, you must use a wrapper class. If the function will be excluding variable arguments, then one way of writing using vargs is

 public static <T> void process(T...args) { System.out.println(Arrays.toString(args)); } 

this concept is used in the java API

0
source

All Articles