我正在尝试通过使用pre[1]将值List <Integer> list = new ArrayList(pre[1]);赋予新列表,但出现了一个空列表。

当我将其分为2个步骤时:首先创建一个空的list1,然后将pre[1]添加到我的list1中,它可以正常工作:list1包含2

谁能告诉我为什么?
我期待着同样的结果。

我当时以为List <Integer> list = new ArrayList(pre[1]);正在创建列表,并将值初始化为pre[1],但是没有用,这是什么问题?

int[] pre =new int []{1,2,3};
List <Integer> list = new  ArrayList(pre[1]);

List <Integer> list1 = new  ArrayList();
list1.add(pre[1]);

最佳答案

请阅读the documentation of ArrayList's constructors

TL; DR:没有构造函数接收初始化的ArrayList应该包含的新元素。
您要调用的构造函数为the one that receives an integer as argument,其容量根据参数(即您的情况下的pre[1]2)定义。

07-24 09:46
查看更多