问题描述
如果某个元素满足特定条件,我想从 Java 中的 ArrayList
中删除该元素.
I would like to remove an element from an ArrayList
in Java if it meets a certain criteria.
即:
for (Pulse p : pulseArray) {
if (p.getCurrent() == null) {
pulseArray.remove(p);
}
}
我能理解为什么这不起作用,但有什么好的方法可以做到这一点?
I can understand why this does not work, but what is a good way to do this?
推荐答案
您必须使用 Iterator
进行迭代,并且迭代器的 remove
函数(不在列表中)) :
You must use an Iterator
to iterate and the remove
function of the iterator (not of the list) :
Iterator<Pulse> iter = pulseArray.iterator();
while (iter.hasNext()) {
Pulse p = iter.next();
if (p.getCurrent()==null) iter.remove();
}
请注意,Iterator#remove 函数据说是可选,但它由 ArrayList 的迭代器实现.
Note that the Iterator#remove function is said to be optionnal but it is implemented by the ArrayList's iterator.
这是来自 ArrayList.java 的这个具体函数的代码:
Here's the code of this concrete function from ArrayList.java :
765 public void remove() {
766 if (lastRet < 0)
767 throw new IllegalStateException();
768 checkForComodification();
769
770 try {
771 ArrayList.this.remove(lastRet);
772 cursor = lastRet;
773 lastRet = -1;
774 expectedModCount = modCount;
775 } catch (IndexOutOfBoundsException ex) {
776 throw new ConcurrentModificationException();
777 }
778 }
779
780 final void checkForComodification() {
781 if (modCount != expectedModCount)
782 throw new ConcurrentModificationException();
783 }
784 }
expectedModCount = modCount;
行就是为什么在迭代时使用它时不会抛出异常的原因.
The expectedModCount = modCount;
line is why it won't throw an exception when you use it while iterating.
这篇关于根据给定条件从 ArrayList 中删除对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!