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?
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).
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);
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];
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With