javaarrays

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


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?


Solution

  • 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 are curious you may have a look at a analogical problem (generics and classes vs. primitive types) with Streams here: https://stackoverflow.com/a/23010472/2886891