Reputation: 14834
Consider this code:
int[] tcc = {1,2,3};
ArrayList<Integer> tc = Arrays.asList(tcc);
For the above, Java complains that it cannot convert from List<int[]>
to ArrayList<Integer>
.
What's wrong with this?
Why is it List<int[]>
and not List<int>
?
Upvotes: 3
Views: 395
Reputation: 16262
You could have it as:
List<int[]> tc = Arrays.asList(tcc);
Arrays.asList returns a List, not an ArrayList. And since Arrays.asList is a varargs function, it thinks tcc
is one element of a bigger array.
If you want to have just a List of Integers, you'd have to rewrite it as SB mentioned in the comments for Hovercraft Of Eel's answer:
List<Integer> tc = Arrays.asList(1, 2, 3);
Alternatively, if you make tcc
an Integer[]
, you can still use your array as an argument in the following snippet by explicitly asking for a List
of Integer, providing a type parameter that agrees with the passed array:
Integer[] tcc = {1,2,3};
List<Integer> tc = Arrays.<Integer>asList(tcc);
Upvotes: 1
Reputation: 713
This will work:
ArrayList tc = new ArrayList(Arrays.asList(1,2,3));
Upvotes: 1
Reputation: 285403
An ArrayList can hold only objects not primitives such as ints, and since int != Integer you can't do what you're trying to do with an array of primitives, simple as that. This will work for an array of Integer though.
Upvotes: 3