java 将元素添加到 List<List<Integer>>
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31064005/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
add elements to List<List<Integer>>
提问by u4582785
I want to add [1] [1,2] [1,2,3] etc to List> but it does not work if I
我想将 [1] [1,2] [1,2,3] 等添加到 List> 但如果我不工作
List<Integer> w = new ArrayList<Integer>();
List<List<Integer>> a = new ArrayList<ArrayList<Integer>>();
for(int i=1;i<n; i++){
w.add(i);
a.add(w);
}
I want each element to not be affected by each other.
我希望每个元素都不会相互影响。
回答by Sanjeev
I guess this is what you are looking for :
我想这就是你要找的:
List<Integer> w = new ArrayList<Integer>();
List<ArrayList<Integer>> a = new ArrayList<ArrayList<Integer>>(); //Use Arraylist inside
for(int i=1;i<10; i++){
w.add(i);
a.add(new ArrayList(w));
}
System.out.println(w);
System.out.println(a);
回答by RadekSohlich
Well I'm assuming that the second list I named a
instead of w
. So the problem here is that, you should make a deep copy of a list that is added to list of lists. Otherwise you are using the same object. Simply add a.add(new ArrayList(w))
.
好吧,我假设我命名的第二个列表a
而不是w
. 所以这里的问题是,你应该制作一个添加到列表列表的列表的深层副本。否则,您将使用相同的对象。只需添加a.add(new ArrayList(w))
.