45

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

1
  • 4
    Use Integer[] instead of int[].
    – sp00m
    Dec 17, 2014 at 9:56

3 Answers 3

56

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());

3
  • 1
    Note that the IntStream approach has slightly different semantics than using asList; changes to the underlying array are not reflected in the resulting list. (so there is a copy of some sort going on). asList(T...) does no copying. I don't know of any way around that, unfortunately.
    – rcreswick
    May 12, 2016 at 14:55
  • @rcreswick Interesting, did not know that. However, if this behaviour is expected, then there's probably really no way to achieve it with an int[], as the int[] could not be the backing array of the resulting List<Integer>.
    – tobias_k
    May 12, 2016 at 14:59
  • I've been trying to find a way to achieve this, and I think the only way is to create a new list type that manages the accesses to reuse a backing array, which would likely obviate the general performance improvements your hope for by using a backing array.
    – rcreswick
    May 14, 2016 at 3:33
17

In Java 8 you can do

List<Integer> list = IntStream.of(a).boxed().collect(Collectors.toList());
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]);
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.