[英]Simple ArrayList.remove(int) doesn't work. What I am doing wrong?
I am trying to iterate through an ArrayList
and remove the actual object (index s) under certain conditions ( x == 0
).我正在尝试遍历
ArrayList
并在某些条件下( x == 0
)删除实际的 object (索引 s)。 It always gives an error at the line where the object should be removed, if executed.如果执行,它总是在应该删除 object 的行处给出错误。 Without the
remove()
it runs perfectly fine.没有
remove()
它运行得非常好。
int s = 0;
int x = 0;
if (!objectList.isEmpty()) {
for (obj actualObj : objectList) {
if (x == 0) {
objectList.remove(s);
} else {
System.out.println("x != 0");
}
s++;
}
} else {
System.out.println("list is empty");
}
My biggest nitpick would be this: you can't mutate/modify the collection you are iterating over (outside of calling Iterator#remove
, etc) when using syntactic sugar like the enhanced for-each loop ( for (T val: Iterable<T>)
).我最大的挑剔是:当使用增强的 for-each 循环( for (T val:
Iterator#remove
for (T val: Iterable<T>)
)。 In fact, Iterator#remove
exists pretty much exactly for this reason:事实上,
Iterator#remove
的存在正是因为这个原因:
int toRemove = 0; //The number to remove from your list
List<Integer> list = /* your list */;
Iterator<Integer> itr = list.iterator(); //Create an iterator of the collection
while (itr.hasNext()) { //while new elements are available...
Integer val = itr.next(); //grab the next available element
if (val == toRemove) { //removal condition
itr.remove(); //remove the last grabbed element from the collection
}
}
If you're capable of using Java 8:如果您能够使用 Java 8:
int toRemove = 0; //The number to remove from your list
List<Integer> list = /* your list */;
list.removeIf(val -> toRemove == val); //didn't use member reference, for clarity reasons
Each time you remove an element from a List
using an index, the List
shrinks because the succeeding elements shift one place left/down.每次使用索引从
List
中删除一个元素时, List
都会缩小,因为随后的元素会向左/向下移动一个位置。 It means that in the next iteration of the loop, you will be actually deleting an element which was next to the next of the last deleted element.这意味着在循环的下一次迭代中,您实际上将删除一个元素,该元素与最后一个删除元素的下一个元素相邻。
For this reason, you should delete elements from a List
in a loop using an Iterator
instead of the index as shown below:出于这个原因,您应该在循环中使用
Iterator
而不是索引从List
中删除元素,如下所示:
Iterator<YourType> itr = objectList.iterator();
while (itr.hasNext()) {
YourType obj = itr.next();
if (some condition) {
itr.remove();
}
// ...
}
you are removing from the list while iterating through it.您在迭代列表时从列表中删除。 A workable option is
一个可行的选择是
int x = 0;
List<String> objectList = Arrays.asList("A", "B", "C");
if (objectList.isEmpty()) System.out.println("list is empty");
List<String> filtered = objectList.stream().filter(s1 -> x != 0).collect(Collectors.toList());
System.out.println(objectList + "\n" + filtered);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.