How can I make a method take an array of any type as a parameter?

I would like to be able to use any type of array as a parameter in a method .:

public void foo(Array[] array) { System.out.println(array.length) } 

Is there a way to pass an array of String [] or int [] in the same method?

+6
source share
4 answers

Use generics .

 public <T>void foo(T[] array) { System.out.println(array.length); } 

This will not work for an array of primitive types such as int[] , boolean[] , double[] , ... Instead, you should use their class wrappers: Integer[] , boolean[] , double[] , ... or overload your method for each necessary primitive type separately.

+6
source

Well, you can do something like this (because the array is an Object) -

 public static int getArrayLength(Object array) { return Array.getLength(array); } public static void main(String[] args) { int[] intArray = { 1, 2, 3 }; String[] stringArray = { "1", "2", "c", "d" }; System.out.println(getArrayLength(intArray)); System.out.println(getArrayLength(stringArray)); } 

Output

 3 4 
+3
source

This may be possible with Generics.

I do not know about that. I recommend that you read about this in the documentation. http://docs.oracle.com/javase/tutorial/java/generics/index.html

Generics works with objects, so I think you cannot pass String [] and int [] in the same method. Use Integer [] instead.

Here is the code I would use:

 public static <K> int length(K[] array){ return array.length; } 

It may also work:

 public static int length(Object[] array){ return array.length; } 

But this will not allow you to use a specific type of object instead of the Object class.

I am completely new at this, perhaps there is a better solution, but this is the only thing I know!

+3
source

As mentioned above, now there is a way to do this if you want to be able to accept arrays of primitive types (unless you are doing something like the Elliott solution where you need and Object and can only go through using methods like Array.getLength (Object), which takes an object as input).

What I am doing is making a generic method and then overloading it for each type of primitive array as follows:

 public <T> void foo(T[] array) { //Do something } public void foo(double[] array) { Double[] dblArray = new Double[array.length]; for(int i = 0; i < array.length; i++){ dblArray[i] = array[i]; } foo(dblArray); } //Repeat for int[], float[], long[], byte[], short[], char[], and boolean[] 
0
source

Source: https://habr.com/ru/post/969661/


All Articles