Iterator and iterable differences and linkages

Source: Internet
Author: User
Tags iterable concurrentmodificationexception

traversing a collection with iterator mode

The iterator pattern is a standard access method for traversing collection classes. It abstracts the access logic from different types of collection classes, thus avoiding exposing the internal structure of the collection to the client.

For example, if iterator is not used, the way to traverse an array is to use the index: for (int i=0; i<array.size (); i++) {...} ...}

Access to a list (LinkedList) must also use the while loop: while ((E=e.next ())!=null) {...} e.data () ...}

Both of these methods the client must know in advance the internal structure of the collection, and the access code and the set itself are tightly coupled . The access logic cannot be detached from the collection class and the client code, and each collection has a corresponding traversal method, and the client code cannot be reused.

Even more frightening, assuming that the ArrayList will need to be replaced with LinkedList later, the original client code must all be rewritten.

Solve the above problems. Iterator mode always uses the same logic to traverse the collection: for (Iterator it = C.iterater (); It.hasnext ();) { ... }

The secret is that the client itself does not maintain a "pointer" that iterates through the collection. All internal states, such as the current element position and whether there is a next element, are maintained by iterator , and this iterator is generated by the collection class through the factory method. Therefore, it knows how to traverse the entire collection.

The client never deals directly with the collection class, it always controls the iterator, sends it "forward", "backwards". "Take the current Element" command, you can indirectly traverse the entire collection.

First look at the definition of the Java.util.Iterator interface:
Public interface Iterator {Boolean hasnext (); Object next (); void Remove (); }

Relying on the first two methods can be completed traversal, typical code such as the following:
for (Iterator it = C.iterator (); It.hasnext ();) {Object o = It.next ();//operation on o ...}

Each collection class may return a different iterator detail type, and an array may return arrayiterator,set that may return setiterator. The tree may return treeiterator, but they all implement the iterator interface. So, the client doesn't care what kind of Iterator it is, it just needs to get the Iterator interface. This is the power of object-oriented.

All collection classes implement the Collection interface, while Collection inherits the Iterable interface.

/** * Implementing this interface allows a object to be the target of * the "foreach" statement. * * @param <T> The type of elements returned by the iterator * * @since 1.5 */public interface iterable<t> {
   /**     * Returns An iterator over a set of elements of type T.     *     * @return an Iterator.     *    /iterator<t> Iterator ();}

In a detailed implementation class (for example, ArrayList), a Itr inner class is maintained internally. The class inherits the Iterator interface, and its hasnext () and Next () methods are coupled to the ArrayList implementation.

When the iterator () method of the ArrayList object is called, an instance of the class Itr is returned, enabling the ability to traverse ArrayList.

Public iterator<e> Iterator () {return new Itr ();        }/** * An optimized version of ABSTRACTLIST.ITR */Private class Itr implements Iterator<e> {       int cursor; Index of next element to return int lastret =-1; Index of last element returned;        -1 if no such int expectedmodcount = Modcount;        public Boolean Hasnext () {return cursor! = size;            } @SuppressWarnings ("Unchecked") public E Next () {checkforcomodification ();            int i = cursor;            if (i >= size) throw new nosuchelementexception ();            object[] Elementdata = ArrayList.this.elementData;            if (i >= elementdata.length) throw new Concurrentmodificationexception ();            cursor = i + 1;        Return (E) Elementdata[lastret = i];  } public void Remove () {if (Lastret < 0) throw new IllegalStateException ();          Checkforcomodification ();                try {ArrayList.this.remove (Lastret);                cursor = Lastret;                Lastret =-1;            Expectedmodcount = Modcount;            } catch (Indexoutofboundsexception ex) {throw new concurrentmodificationexception (); }} final void Checkforcomodification () {if (Modcount! = expectedmodcount) Throw        New Concurrentmodificationexception (); }    }

Why do you have to implement iterable this interface? Why not implement the iterator interface directly?

Take a look at the collection classes in the JDK, such as the list family or set family, which implements the Iterable interface. However, the iterator interface is not implemented directly. It makes sense to think about it in detail.

Because the core method of the Iterator interface next () or Hasnext () is dependent on the current iteration position of the iterator.

Suppose collection implements the iterator interface directly. is bound to cause data (pointers) in the collection object to include the current iteration position. When a collection is passed between different methods, the result of the next () method becomes unpredictable because the current iteration position is not pre-provisioned.

Unless a reset () method is added to the iterator interface, it is used to reset the current iteration position. But in this case, collection can only have a current iteration position at the same time .

Instead, Iterable returns an iterator that counts from the beginning of each invocation. Multiple iterators are non-interfering.


Iterator and iterable differences and linkages

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.