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

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

    It could be possible using Generics.

    I you don't know about it I recommend you to read about it in the documentation. http://docs.oracle.com/javase/tutorial/java/generics/index.html

    Generics works with Objects so I think you can't pass a String[] and a int[] in the same method. Use Integer[] instead.

    Here is the code I would use:

    public static  int  length(K[] array){
        return array.length;
    }
    

    Also this could work:

    public static int  length(Object[] array){
        return array.length;
    }
    

    But it won't allow you to use a specific type of Object instead of Object class.

    I'm quite new in this, maybe there is a better solution, but it's the only I know!

提交回复
热议问题