Before we implemented the iterator pattern, many programming languages actually had built-in iterator classes, such as Java, which implemented the iterator iterator for us. We first look at the source code in iterator.
Through the JDK source we found that iterator is an interface that contains three methods: Hasnext, Next, and remove.
650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Margin:0px;padding:0px;border:none; "/>
1 package java.util; 2 3 public interface iterator<e> { 4 5 /** 6 * returns True if there are elements in the iterator 7 */ 8 boolean hasnext (); 9 10 /**11 * returns the next element in the iterator 12 */13 e next (); 14 15 /**16 * removes the bottommost element in the collection by Iterators 17 */18 void remove (); 19 }
650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Margin:0px;padding:0px;border:none; "/>
Iterator is an interface, so how do you create an instance? Keep in mind that iterators and collection classes are very closely related, and we can create a iterator instance from a collection class, and ArrayList, LinkedList, and vector have implementations of it. Let's see how ArrayList creates an instance of an iterator iterator. Let's start by looking at the inheritance relationship between the collection and the iterator.
650) this.width=650; "Src=" http://images2015.cnblogs.com/blog/630246/201609/630246-20160930000425344-1253264643. PNG "style=" margin:0px;padding:0px;border:0px;width:686px; "/>
Because the relationship of the collection is relatively complex, here we mainly look at the comment section, by reading the source code will find that ArrayList Abstractlist abstract class iterator method and claim that the effect is better, and LinkedList is not overwrite, Thus, it can be judged that the iterator method of ArrayList is more efficient than the iterator method in LinkedList.
We look directly at the iterator method implemented in ArrayList.
1 public iterator<e> Iterator () {2 return new Itr (); 3}
From the code, it returns a Itr object instance of the class, and follows the code to see what this ITR class is.
650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Margin:0px;padding:0px;border:none; "/>
1 private class Itr implements Iterator<E> { 2 int cursor; // returns the index of the next element 3 int lastRet = -1; // returns the index of the last element, or -1 4 if none int expectedModCount = modCount; 5 6 public boolean hasnext () { 7 return cursor != size; 8 } 9 10 @SuppressWarnings ("Unchecked") 11 public e next () {12 checkforcomodification ();13 int i = cursor;14 if (I&NBSP;>=&NBSp;size) 15 throw new Nosuchelementexception (); 16 object[] elementdata = ArrayList.this.elementData;17 if (i >= elementdata.length) 18 throw new concurrentmodificationexception ();19 cursor = i + 1;20 return ( E) elementData[lastRet = i];21 }22 23 public void remove () {24 if ( lastret < 0) 25 throw new illegalStateexception (); 26 checkforcomodification (); 27 28 try {29 arraylist.this.remove (Lastret);30 cursor = lastRet;31 lastRet = -1;32 expectedModCount = modCount;33 } catch (Indexoutofboundsexception ex) {34 throw new concurrentmodificationexception (); 35 }36 }37 38 final&nbsP;void checkforcomodification () {39 if ( Modcount != expectedmodcount) 40 throw new concurrentmodificationexception (); 41 }42 }
650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Margin:0px;padding:0px;border:none; "/>
Originally ITR It is a private inner class that implements the iterator interface.
Let's read one line at a time. There is a Modcount variable in line 3rd. Follow this variable and find this variable a bit interesting:
protected transient int modcount = 0;
Found that there is a "transient" keyword, look up the data find this keyword means: Indicates that a domain is not part of the serialization of the object. This means that the variable is not included when the object is serialized, and we can leave a question as to why we should do so. (The JDK source note says so: The Modcount value, the iterator believes that the backing List should has. If this expectation was violated, the iterator has detected concurrent modification. English too can only read the last sentence: if the expectation is visibility, then the iterator detects a concurrent modification. Guessing is associated with concurrent multithreading. )
The implementation of Hasnext is simple:
1 public boolean Hasnext () {2 return cursor! = size; Whether the index of the next element equals the size of ArrayList 3}
Next's implementation:
650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Margin:0px;padding:0px;border:none; "/>
public e next () { checkforcomodification (); Check if concurrent modification int i = cursor; if (i >= size) throw new nosuchelementexception (); Index greater than ArrayList size throws exception Object[] elementData = ArrayList.this.elementData; The following is actually the data in the fetch ArrayList if (i >= elementdata.length) throw new concurrentmodificationexception (); cursor = i + 1; return (E) elementdata[lastret = i];}
650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Margin:0px;padding:0px;border:none; "/>
In the next method we see a checkforcommodification method:
final void Checkforcomodification () {if (Modcount! = expectedmodcount) throw new Concurrentmodificationexceptio n ();}
It seems that this modcount variable is indeed associated with concurrency, and if the values of Expectedmodcount and Modcount are different, the exception that is currently being modified is thrown.
Finally, let's look at the implementation of the Remove method:
650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Margin:0px;padding:0px;border:none; "/>
public void remove () { if (lastret < 0)//This place pays extra attention, You cannot call the Remove method directly without calling next, you must call the next method before the remove call and assign its value to the lastret by the cursor index value throw new illegalstateexception (); checkforcomodification (); try { arraylist.this.remove ( Lastret); cursor = lastret; lastRet = -1; expectedmodcount = modcount; } catch (IndexOutOfBoundsException &NBSP;EX) { throw new Concurrentmodificationexception (); }}
650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Margin:0px;padding:0px;border:none; "/>
In the Remove method we should pay extra attention, in the first sentence is to detect whether Lastret is less than 0, we initialized the Lastret variable-1 value, which means that If we call the Remove method directly after creating the iterator instance to throw a IllegalStateException exception, how can we call it correctly? That is, call the Remove method before calling the next method, at which point the Lastreturn is assigned by the cursor index, and the Remove method can be used correctly. It also calls the Checkforcommodification method to do concurrent modification detection. In fact, we can see the JDK source code is written well, because it has done a lot of testing each method, to ensure that in as many scenarios as possible to run correctly. Today's Java iterator is a simple introduction through the JDK source code, through the source of reading can deepen our understanding, this is just a simple reading, and did not do a very deep understanding. Finally, we think of a iterator example ending.
650) this.width= 650, "src="/img/fz.gif "alt=" Copy Code "style=" Margin:0px;padding:0px;border:none; "/>
1 package day_29_iterator; 2 3 import java.util.arraylist; 4 import java.util.iterator; 5 import java.util.list; 6 7 /** 8 * @author turbo 9 *10 * 2016 September 29 11 * /12 public class main {13 14 /**15 * @param args16 */17 public static void main (String[] args) {18 list list = new arraylist ();19 list.add (1); 20 list.add (2);21 iterator iterator = list.iterator ();22 while (Iterator.hasnext ()) {23 system.out.println (Iterator.next ()); 24 }25 }26 27 }
650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Margin:0px;padding:0px;border:none; "/>
Java iterator iterator