System: OS: OS X 10.9
What does an iterator and why we need to use them? When we need them? How to remove element from list while iterating?
Java implementations of iterators like collection interface for save looping through collection. In a practice the best situation where you can apply iterator are removing element from list.
For example try to run this code:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
public static void iteratorTest() { final List list = new ArrayList<>(); list.add("item1"); list.add("item2"); list.add("item3"); list.add("item4"); for (final String item : list) { if (item.equals("item2")) { list.remove(item); } } } |
Result of such code will be an error:
1 |
Exception in thread “main" java.util.ConcurrentModificationException |
That is happened because in the code we tried to remove element from the list while lopping through this list. To solve this problem and work with collections safety we can use iterator.
Good practice to remove element from list looks like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
public static void iteratorTest() { final List list = new ArrayList<>(); list.add("item1"); list.add("item2"); list.add("item3"); list.add("item4"); Iterator iterator = list.iterator();// create iterator while (iterator.hasNext()) { // looping with 'while' loop final String item = iterator.next(); if (item.equals("item2")) { iterator.remove(); // remove element } } } |
Also using iterators can be applicable for anther scenarios where you want modify original collection safely.