0

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
}
4
  • 2
    Generics doesn't work with primitive types, it's for objects only. Try with new Integer[1], 0 instead. Commented Apr 9, 2016 at 14:27
  • It's also a reason why Double, Integer, Boolean,... is created in Java. Commented Apr 9, 2016 at 14:35
  • What do you mean when you say primitives don't work with generic types? int works just fine, it's just the array which is causing issues Commented Apr 10, 2016 at 16:04
  • By the way, in this case, the generics is useless. It would be identical if declared as public static void method(Object[] array, Object value) Commented Apr 12, 2016 at 0:33

3 Answers 3

1

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);
Sign up to request clarification or add additional context in comments.

Comments

1

You could use Integer instead of int, since generics don't work with primitive types.

Comments

0

why use primitive type here. Generics only work with referenced type.

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

better to go with

 method(new Integer[]{1,2,3,4}, 0); //works fine

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.