albertos
albertos

Reputation: 47

How to use int in place of T in a Java generic method?

I have this method that I just want to let it accept a multi dimensional array of any type.

Here is the current code:

public static <T> T[] aMethod(T[][] multiDimentionalArray) {
    return null;
}

and when I try it out with something like:

int[][] a = new int[][] {{1,2,3,4},{2}};
aMethod(a);

I keep getting an error to change the aMethod parameter type to int[][].. so why is this happening, don't I have generic type applied?

Upvotes: 2

Views: 1273

Answers (4)

ruohola
ruohola

Reputation: 24077

You cannot use a primitive type, such as int, as the concrete type for a generic method. You need to use something that inherits from Object, like the Integer type:

Integer[][] a = new Integer[][] {{1, 2, 3, 4}, {2}};
aMethod(a);

The reason for this is that Java generics are implemented using type erasure and any concrete type will be replaced with their type bounds or Object if they are unbounded.

Upvotes: 0

user9386531
user9386531

Reputation:

Change your code to this:

public static <T> T aMethod(T multiDimentionalArray) {
     return null;
}

This works for you.

Upvotes: 0

Youcef LAIDANI
Youcef LAIDANI

Reputation: 60016

You have to use Integer instead of int, because T should be an Object, and int is a primitive type :

Integer[][] a = new Integer[][]{{1, 2, 3, 4}, {2}};

If you want to pass an array of int[][], in this case you have to change the signature of your method, to be :

public static <T> T[] aMethod(T[] multiDimentionalArray) {

But in case(I don't suggest this) to work with array or array you need to cast your value to help the compiler to understand what happen for example :

public static <T> void aMethod(T[] multiDimentionalArray) {
    for (int[] t : (int[][]) multiDimentionalArray) {
        System.out.println(Arrays.toString(t));
    }
}

Upvotes: 3

bathudaide
bathudaide

Reputation: 747

See java docs

Cannot Instantiate Generic Types with Primitive Types

change to

Integer[][] a = new Integer[][] {{1, 2, 3, 4}, {2}};

Upvotes: 0

Related Questions