Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

arrays

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

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

Is there a way where I could pass a String[] or int[] array, in the same method?

like image 618
TACO Avatar asked May 21 '14 20:05

TACO


People also ask

Can a method take an array as a parameter?

You can pass arrays to a method just like normal variables. When we pass an array to a method as an argument, actually the address of the array in the memory is passed (reference).

How do you call an array method as a parameter?

To pass an array as an argument to a method, you just have to pass the name of the array without square brackets. The method prototype should match to accept the argument of the array type. Given below is the method prototype: void method_name (int [] array);

How do you pass an array of Objects as a parameter?

Passing array of objects as parameter in C++ Array of Objects:It is an array whose elements are of the class type. It can be declared as an array of any datatype. Syntax: classname array_name [size];


1 Answers

Use generics.

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

This will not work for array of primitive types, such as int[], boolean[], double[],... You have to use their class wrappers instead: Integer[], Boolean[], Double[], ... or overload your method for each needed primitive type separately.

like image 171
Honza Zidek Avatar answered Sep 28 '22 01:09

Honza Zidek