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

后端 未结 4 1703
耶瑟儿~
耶瑟儿~ 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:19

    Well, you can do something like this (because an array is an Object) -

    public static int getArrayLength(Object array) {
        return Array.getLength(array);
    }
    
    public static void main(String[] args) {
        int[] intArray = { 1, 2, 3 };
        String[] stringArray = { "1", "2", "c", "d" };
        System.out.println(getArrayLength(intArray));
        System.out.println(getArrayLength(stringArray));
    }
    

    Output is

    3
    4
    

提交回复
热议问题