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

后端 未结 4 1704
耶瑟儿~
耶瑟儿~ 2021-01-12 13:19

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)
}
         


        
4条回答
  •  花落未央
    2021-01-12 13:58

    Use generics.

    public 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.

提交回复
热议问题