Initialize ArrayList

后端 未结 4 1582
我寻月下人不归
我寻月下人不归 2021-01-05 03:25

Why I can initialize ArrayList, like this:

ArrayList x = new ArrayList(Arrays.asList(1,2));

But got Error whe

4条回答
  •  耶瑟儿~
    2021-01-05 04:11

    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 ints into longs 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);
    

提交回复
热议问题