With a for each loop you can iterate easily through a collection but you cannot remove elements during iteration.
List<String> list = new ArrayList<String>();
list.add("Max");
list.add("bob");
list.add("Alex");
// for each loop:
// execution this loop ends with a
// java.util.ConcurrentModificationException
for (String element : list) {
list.remove(element);
}
A java.util.Iterator is a suitable solution for the above situation, because it allows you to remove elements from a collection during iteration.Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
iterator.next());
iterator.remove();
}
Iterator interface has three methods:boolean hasNext() E next() void remove()and allows for iteration in a one direction. If you want to iterate through a list in both directions you should use a ListIterator (implements Iterator) which has additional methods:
boolean hasPrevious() E previous() int previousIndex() int nextIndex()
Comments
Post a Comment