What are the benefits of the Iterator interface in Java?

后端 未结 16 1923
没有蜡笔的小新
没有蜡笔的小新 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:06

    Multiple instances of an interator can be used concurrently. Approach them as local cursors for the underlying data.

    BTW: favoring interfaces over concrete implementations looses coupling

    Look for the iterator design pattern, and here: http://en.wikipedia.org/wiki/Iterator

    0 讨论(0)
  • 2020-12-04 15:10

    Iterators are one of the many design patterns available in java. Design patterns can be thought of as convenient building blocks, styles, usage of your code/structure.

    To read more about the Iterator design pattern check out the this website that talks about Iterator as well as many other design patterns. Here is a snippet from the site on Iterator: http://www.patterndepot.com/put/8/Behavioral.html

    The Iterator is one of the simplest and most frequently used of the design patterns. The Iterator pattern allows you to move through a list or collection of data using a standard interface without having to know the details of the internal representations of that data. In addition you can also define special iterators that perform some special processing and return only specified elements of the data collection.

    0 讨论(0)
  • 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<E> {
    
            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<E> {
             //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.

    0 讨论(0)
  • 2020-12-04 15:13

    Because you may be iterating over something that's not a data structure. Let's say I have a networked application that pulls results from a server. I can return an Iterator wrapper around those results and stream them through any standard code that accepts an Iterator object.

    Think of it as a key part of a good MVC design. The data has to get from the Model (i.e. data structure) to the View somehow. Using an Iterator as a go-between ensures that the implementation of the Model is never exposed. You could be keeping a LinkedList in memory, pulling information out of a decryption algorithm, or wrapping JDBC calls. It simply doesn't matter to the view, because the view only cares about the Iterator interface.

    0 讨论(0)
  • 2020-12-04 15:14

    I think it is just good OO practice. You can have code that deals with all kinds of iterators, and even gives you the opportunity to create your own data structures or just generic classes that implement the iterator interface. You don't have to worry about what kind of implementation is behind it.

    0 讨论(0)
  • 2020-12-04 15:17

    Using the Iterator interface allows any class that implements its methods to act as iterators. The notion of an interface in Java is to have, in a way, a contractual obligation to provide certain functionalities in a class that implements the interface, to act in a way that is required by the interface. Since the contractual obligations must be met in order to be a valid class, other classes which see the class implements the interface and thus reassured to know that the class will have those certain functionalities.

    In this example, rather than implement the methods (hasNext(), next(), remove()) in the LinkedList class itself, the LinkedList class will declare that it implements the Iterator interface, so others know that the LinkedList can be used as an iterator. In turn, the LinkedList class will implement the methods from the Iterator interface (such as hasNext()), so it can function like an iterator.

    In other words, implementing an interface is a object-oriented programming notion to let others know that a certain class has what it takes to be what it claims to be.

    This notion is enforced by having methods that must be implemented by a class that implements the interface. This makes sure that other classes that want to use the class that implements the Iterator interface that it will indeed have methods that Iterators should have, such as hasNext().

    Also, it should be noted that since Java does not have multiple inheritance, the use of interface can be used to emulate that feature. By implementing multiple interfaces, one can have a class that is a subclass to inherit some features, yet also "inherit" the features of another by implementing an interface. One example would be, if I wanted to have a subclass of the LinkedList class called ReversibleLinkedList which could iterate in reverse order, I may create an interface called ReverseIterator and enforce that it provide a previous() method. Since the LinkedList already implements Iterator, the new reversible list would have implemented both the Iterator and ReverseIterator interfaces.

    You can read more about interfaces from What is an Interface? from The Java Tutorial from Sun.

    0 讨论(0)
提交回复
热议问题