Java 创建 subList 并从以前的 List 中删除值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16634215/
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
Java create subList and remove values from previous List
提问by Erik
I want to create a subList in Java and remove values that are in subList from the previous List. My program correctly creates subList, but than it doesn't remove the correct values from previousList.
我想用 Java 创建一个 subList 并从以前的 List 中删除 subList 中的值。我的程序正确创建了 subList,但它没有从 previousList 中删除正确的值。
My Code:
我的代码:
for(int i=0; i<4; i++){
List<Object> sub=new ArrayList<Object>(prevoiusList.subList(0,6));
for (int j=0; j<6; j++){
previousList.remove(j);
}
}
回答by BobTheBuilder
At first j=0
and you remove the first element. When doing so you shift all other elements, so the second element becomes first and so on.
首先j=0
,您删除第一个元素。这样做时,您将移动所有其他元素,因此第二个元素成为第一个,依此类推。
On next iteration j=1
, so you remove the second element, which was originally the third...
在下一次迭代中j=1
,删除第二个元素,它最初是第三个......
In order to fix this issue, use only 0
index, or an iterator.
为了解决这个问题,只使用0
索引或迭代器。
回答by naveejr
Do it in a single line
在一行中完成
prevoiusList.subList(0,6).clear()
回答by Mustafa Gen?
Why dont you just do :
你为什么不这样做:
previousList = previousList.subList(7, previousList.size());
回答by Bohemian
To "move" 6 elements from one list to create another list:
要从一个列表中“移动”6 个元素以创建另一个列表:
List<Object> list;
List<Object> subList = new ArrayList<Object>(list.subList(0, 6));
list.removeAll(subList);
It should be noted that List.subList()
, returns a viewof the list, so modifications to the origianl list will be reflected in the sub list, hence creating the new list and passing the sub list to the constructor.
需要注意的是List.subList()
, , 返回列表的视图,因此对原始列表的修改将反映在子列表中,因此创建新列表并将子列表传递给构造函数。
To put this in a loop:
把它放在一个循环中:
List<Object> list;
while (list.size() > 5) {
List<Object> subList = new ArrayList<Object>(list.subList(0, 6));
list.removeAll(subList);
// do something with subList
}
// list now has 0-5 elements