Search code examples
javaarraysgenericstype-inferencegeneric-method

Java - type inference for array paramater of a generic method


Type inference doesn't seem to work for arrays with generic methods? I receive the error 'The method contains(T[], T) is not applicable for the arguments (int[], int)'. How should I be doing this?

method(new int[1], 0); //Error

...

public static <T> void method(T[] array, T value) {
    //Implement
}

Solution

  • Generics doesn't work with primitive types, only with object types.

    You can do what looks like using generics with primitive types, due to auto-boxing:

    <T> void methodOne(T value) {}
    
    methodOne(1);  // Compiles OK, T = Integer.
    

    What is actually happening here is that the int literal 1 is being "boxed" to Integer.valueOf(1), which is an object of type Integer.

    You can pass also an int[] to a generic method, because int[] is an object type itself. So:

    methodOne(new int[1]);  // Compiles OK, T = int[].
    

    However, you can't mix these two with the same type variable: int[] and Integer are not related types, so there is no single type variable T which is satisfied by both parameters. There is no equivalent auto-boxing operator from int[] to Integer[].

    As such, you would need to pass an Integer[] array as the first parameter:

    method(new Integer[1], 0);