javajava-collections-api

List difference with list constructed by Arrays.asList has surprising result. Why?


What value for "zs" do you expect after the following snippet has run?

Collection<Integer> xs = Arrays.asList(1,2,3);
int[] ys = {1};
List<Integer> zs = new ArrayList<>(xs);
zs.removeAll(Arrays.asList(ys));

I would have expected a list containing 2 and 3. However, with JDK 1.8.0_25 in Eclipse 4.5 M7 it is a list containing 1, 2, 3. The removal has no effect. However, when I specify "ys" as a non-primitive array, I get the expected result:

Collection<Integer> xs = Arrays.asList(1,2,3);
Integer[] ys = {1};
List<Integer> zs = new ArrayList<>(xs);
zs.removeAll(Arrays.asList(ys));

What's going on here?


Solution

  • The type of Arrays.asList(int[]) is List<int[]>. As such, none of the elements in xs is contained in that list.