问题描述
如果符合某个条件,我想从Java中的 ArrayList
中删除一个元素。
I would like to remove an element from an ArrayList
in Java if it meets a certain criteria.
ie:
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?
推荐答案
你必须使用迭代器
迭代和迭代器的删除
函数(不是列表):
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();
}
请注意函数被认为是optionnal但是由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中删除对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!