44

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

PDStat
  • 5,513
  • 10
  • 51
  • 86

3 Answers3

55

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

tobias_k
  • 81,265
  • 12
  • 120
  • 179
  • 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 '16 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`. – tobias_k May 12 '16 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 '16 at 03:33
17

In Java 8 you can do

List<Integer> list = IntStream.of(a).boxed().collect(Collectors.toList());
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
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]);
}
Sagar Koshti
  • 408
  • 2
  • 6
  • 15