java : Understanding Arrays.asList(T...array) method for primitive types
There are obviously 3 questions here so lets tackle them one by one:
- 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.
- 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());
You are not getting a Lit or a List (which can't be), you're getting a List of arrays of integer.
So your list does not contain 211, it contains an array that then contains 211.
The array is not "unrolled" into the list, it is added "as is" to a newly created list.
So :
System.out.println(Arrays.asList(array).contains(array)); // Will return trueSystem.out.println(Arrays.asList(a).contains(a)); // Will return true
It is because Arrays.asList()
is a variadic generic function. Change this,
int[] array = {210,211,212};
to
Integer[] array = { 210, 211, 212 };
And the output will be true
and true
.