You can iterate over the list this way ...
public void clean(List<Kopek> kopeks) { for(Kopek kopek : kopeks) { if (kopek.isDirty()) kopeks.remove(kopek); } }
Which is equivalent ...
public void clean1(List<Kopek> kopeks) { Iterator<Kopek> kopekIter = kopeks.iterator(); while (kopekIter.hasNext()) { Kopek kopek = kopekIter.next(); if (kopek.isDirty()) kopeks.remove(kopek); } }
Do not do this ... (due to what you have already observed.)
public void clean(List<Kopek> kopeks) { for(int i=0; i<kopeks.size(); i++) { Kopek kopek = kopeks.get(i); if (kopek.isDirty()) kopeks.remove(i); } }
However, I believe that deleting by index rather than by object is more efficient. Removing an object is inefficient because the list is in most cases not hashed.
kopeks.remove (penny);
vs
kopeks.remove (i);
To achieve positional removal by treating a moving target accordingly ...
public void clean(List<Kopek> kopeks) { int i=0; while(i<kopeks.size()) { Kopek kopek = kopeks.get(i); if (kopek.isDirty())
source share