incompatible types: inference variable T has incompatible bounds [duplicate]

I have the following piece of code

public int solution(int X, int[] A) {

    List<Integer> list = Arrays.asList(A);

For some reason it's throwing the following compilation error

Solution.java:11: error: incompatible types: inference variable T has incompatible bounds List list = Arrays.asList(A); ^ equality constraints: Integer lower bounds: int[] where T is a type-variable: T extends Object declared in method asList(T...)

I assume this a Java 8 feature, but I'm not sure how to resolve the error


Solution 1:

Arrays.asList is expecting a variable number of Object. int is not an Object, but int[] is, thus Arrays.asList(A) will create a List<int[]> with just one element.

You can use IntStream.of(A).boxed().collect(Collectors.toList());

Solution 2:

In Java 8 you can do

List<Integer> list = IntStream.of(a).boxed().collect(Collectors.toList());

Solution 3:

There is no shortcut for converting from int[] to List as Arrays.asList does not deal with boxing and will just create a List which is not what you want. You have to make a utility method.

int[] ints = {1, 2, 3};
List<Integer> intList = new ArrayList<Integer>();
for (int index = 0; index < ints.length; index++)
{
    intList.add(ints[index]);
}