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
Iteratorto iterate and theremovefunction of the iterator (not of the list) :Note that the Iterator#remove function is said to be optionnal but it is implemented by the ArrayList’s iterator.
Here’s the code of this concrete function from ArrayList.java :
The
expectedModCount = modCount;line is why it won’t throw an exception when you use it while iterating.