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

后端 未结 4 1702
耶瑟儿~
耶瑟儿~ 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 14:17

    As some others have mentioned, there is now way to do this if you want to be able to accept arrays of primitive types as well (unless you are doing something like in Elliott's solution where you only need and Object and can get by only using methods like Array.getLength(Object) that takes an Object as input).

    What I do is make a generic method and then overload it for each primitive array type like so:

    public  void foo(T[] array) {
        //Do something
    }
    
    public void foo(double[] array) {
        Double[] dblArray = new Double[array.length];
    
        for(int i = 0; i < array.length; i++){
            dblArray[i] = array[i];
        }
        foo(dblArray);
    }
    //Repeat for int[], float[], long[], byte[], short[], char[], and boolean[]
    

提交回复
热议问题