TACO
TACO

Reputation: 145

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?

Upvotes: 10

Views: 14510

Answers (4)

Honza Zidek
Honza Zidek

Reputation: 20226

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.

If you are curious you may have a look at a analogical problem (generics and classes vs. primitive types) with Streams here: https://stackoverflow.com/a/23010472/2886891

Upvotes: 14

NateW
NateW

Reputation: 968

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

Upvotes: 0

Joan
Joan

Reputation: 31

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!

Upvotes: 3

Elliott Frisch
Elliott Frisch

Reputation: 201487

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

Upvotes: 4

Related Questions