Iterator and iterable differences and linkages

Source: Internet
Author: User
Tags iterable concurrentmodificationexception

Ext.: http://blog.csdn.net/zq602316498/article/details/39337899

traversing a collection with iterator mode

The iterator pattern is the standard access method used to traverse the collection class. 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 you are not using iterator, the way to traverse an array is to use the index: for (int i=0; i<array.size (); i++) {...} ...}

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

Both methods the client must know in advance the internal structure of the collection, the Access code and the collection itself is tightly coupled , unable to separate the access logic from the collection class and client code, each collection corresponding to a traversal method, the client code can not be reused.

Even more frightening, if you later need to change ArrayList to LinkedList, the original client code must all be rewritten.

To solve the above problem, the Iterator pattern 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, and that all internal states (such as the current element's position and whether there is a next element) are maintained by iterator , and this iterator is generated by a factory method of the collection class, so it knows how to traverse the entire collection.

The client never deals directly with the collection class, it always controls the iterator, sends a "forward", "backward", "Fetch current" command to it, and can traverse the entire collection indirectly.

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

Depending on the first two methods you can complete the traversal, the typical code is as follows:
for (Iterator it = C.iterator (); It.hasnext ();) {Object o = It.next ();//operation on o ...}

Each collection class may return a different iterator specific type, and the array may return Arrayiterator,set may return Setiterator,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, which is the power of object-oriented.

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

[Java]View PlainCopy 
  1. /**
  2. * Implementing this interface allows a object to be the target of
  3. * the "foreach" statement.
  4. *
  5. * @param <T> The type of elements returned by the iterator
  6. *
  7. * @since 1.5
  8. */
  9. Public interface Iterable<t> {
  10. /** 
  11. * Returns an iterator over a set of elements of type T.
  12. *
  13. * @return an Iterator.
  14. */
  15. Iterator<t> Iterator ();
  16. }

In a specific implementation class (such as ArrayList), a Itr inner class is maintained internally, which 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.

[Java]View PlainCopy  
  1. Public iterator<e> Iterator () {
  2. return new Itr ();
  3. }
  4. /** 
  5. * An optimized version of ABSTRACTLIST.ITR
  6. */
  7. private class Itr implements iterator<e> {
  8. int cursor; //Index of next element to return
  9. int lastret =-1; //Index of last element returned;-1 if no such
  10. int expectedmodcount = Modcount;
  11. Public Boolean hasnext () {
  12. return cursor! = size;
  13. }
  14. @SuppressWarnings ("unchecked")
  15. Public E Next () {
  16. Checkforcomodification ();
  17. int i = cursor;
  18. if (i >= size)
  19. throw new Nosuchelementexception ();
  20. object[] Elementdata = ArrayList.  This.elementdata;
  21. if (i >= elementdata.length)
  22. throw new Concurrentmodificationexception ();
  23. cursor = i + 1;
  24. return (E) Elementdata[lastret = i];
  25. }
  26. public Void Remove () {
  27. if (Lastret < 0)
  28. throw new IllegalStateException ();
  29. Checkforcomodification ();
  30. try {
  31. ArrayList.  This.remove (Lastret);
  32. cursor = Lastret;
  33. Lastret =-1;
  34. Expectedmodcount = Modcount;
  35. } catch (Indexoutofboundsexception ex) {
  36. throw new Concurrentmodificationexception ();
  37. }
  38. }
  39. final void Checkforcomodification () {
  40. if (modcount! = expectedmodcount)
  41. throw new Concurrentmodificationexception ();
  42. }
  43. }

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

Look at the collection classes in the JDK, such as the list family or set family, are implemented Iterable interface, but do not directly implement the iterator interface. It makes sense to think carefully about it.

Because the core method of the Iterator interface next () or Hasnext () is dependent on the current iteration position of the iterator. If collection implements the iterator interface directly, it is bound to cause the collection object to contain the data (pointers) of 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 you add a reset () method to the iterator interface, you can reset the current iteration position. But in this case, collection can only have one current iteration position at a time . Instead, iterable returns an iterator (a new iterator ) that counts from the beginning of each call . 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.