java : Understanding Arrays.asList(T…array) method for primitive types

There are obviously 3 questions here so lets tackle them one by one:

  1. How exactly do I expect that list methods will work when I’m expecting an List of Integer and getting a List of int[] ?

Well, List methods will work exactly as expected, a List<T> is a list of types T. Here T is an int[] so a List<int[]> will contains arrays as each element:

[{1, 2}, {3, 4}, {1, 6}]

So get(i) will return the ith element. In the case of Arrays.asList the List contains a single element, namely the int[] so:

int[] array = {210,211,212};
List<int[]> list = Arrays.asList(array);

Will be

[{210, 211, 212}]

And so

list.get(0)[0] == 210

In case of Strings the return type is List of String and not List of String[]. What sort of implementation differences are there?

String is an Object, not a primitive type. The difference follows from that.

  1. What good is this method for primitives if things are so uncertain?

Things are not uncertain. This method results in defined and predictable behaviour. It’s just not very useful for primitives. This is (yet another) side effect of combining Java’s type system with generics.

Note with Java 8 the conversion of an int[] to a List<Integer> is very simple:

List<Integer> list = Arrays.stream(array).
        boxed().
        collect(toList());

Leave a Comment