简体   繁体   中英

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?

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.

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

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 <K> 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!

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 <T> 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[]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM