Why I can initialize ArrayList, like this:
ArrayList x = new ArrayList(Arrays.asList(1,2));
But got Error whe
That's because 1
and 2
are ints and Arrays.asList(1, 2)
creates a List
.
And the copy constructor of ArrayList
requires the argument to be of the same generic type.
You have several options but the simplest one is to change the int
s into long
s by adding a L
suffix:
List x = new ArrayList(Arrays.asList(1L, 2L));
Note that with Java 9 you can also write:
List x = List.of(1L, 2L);