What are the benefits of the Iterator interface in Java?

后端 未结 16 1954
没有蜡笔的小新
没有蜡笔的小新 2020-12-04 14:35

I just learned about how the Java Collections Framework implements data structures in linked lists. From what I understand, Iterators are a way of traversing th

16条回答
  •  忘掉有多难
    2020-12-04 15:12

    The java.util.Iterator interface is used in the Java Collections Framework to allow modification of the collection while still iterating through it. If you just want to cleanly iterate over an entire collection, use a for-each instead, but a upside of Iterators is the functionality that you get: a optional remove() operation, and even better for the List Iterator interface, which offers add() and set() operations too. Both of these interfaces allow you to iterate over a collection and changing it structurally at the same time. Trying to modify a collection while iterating through it with a for-each would throw a ConcurrentModificationException, usually because the collection is unexpectedly modified!

    Take a look at the ArrayList class

    It has 2 private classes inside it (inner classes) called Itr and ListItr

    They implement Iterator and the ListIterator interfaces respectively

    public class ArrayList..... { //enclosing class

      private class Itr implements Iterator {
    
            public E next() {
                return ArrayList.this.get(index++); //rough, not exact
            }
    
            //we have to use ArrayList.this.get() so the compiler will
            //know that we are referring to the methods in the 
            //enclosing ArrayList class
    
            public void remove() {
                ArrayList.this.remove(prevIndex);
            }
    
            //checks for...co mod of the list
            final void checkForComodification() {  //ListItr gets this method as well
                 if (ArrayList.this.modCount != expectedModCount) { 
                     throw new ConcurrentModificationException();
                 }
            }
      }
    
      private class ListItr extends Itr implements ListIterator {
             //methods inherted....
            public void add(E e) {
                ArrayList.this.add(cursor, e);
            }
    
            public void set(E e) {
                ArrayList.this.set(cursor, e);
            }
      }
    

    }

    When you call the methods iterator() and listIterator(), they return a new instance of the private class Itr or ListItr, and since these inner classes are "within" the enclosing ArrayList class, they can freely modify the ArrayList without triggering a ConcurrentModificationException, unless you change the list at the same time (conccurently) through set() add() or remove() methods of the ArrayList class.

提交回复
热议问题