Java – how to make a method take any type of array as a parameter?
•
Java
I want to be able to take any array type as an argument in the method:
public void foo(Array[] array) { System.out.println(array.length) }
Is there any way to pass a string [] or int [] array in the same method?
Solution
Using genetics
public <T>void foo(T[] array) { System.out.println(array.length); }
This does not work for arrays of basic types, such as int [], Boolean [], double [],... You must use their class wrapper: integer [], Boolean [], double [] Or overload your methods separately for each required base type
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码