Traversing the list in Java will use the Java-provided Iterator, Iterator is very useful, because:
An iterator is a design pattern that is an object that can traverse and select objects in a sequence, and the developer does not need to know the underlying structure of the sequence. Iterators are often referred to as "lightweight" objects because they are less expensive to create.
The iterator functionality in Java is relatively simple and can only be moved one way:
(1) Use method iterator () requires the container to return a iterator. The first time you call Iterator's next () method, it returns the first element of a sequence. Note: The iterator () method is an Java.lang.Iterable interface that is inherited by collection.
(2) Use Next () to get the next element in the sequence.
(3) Use Hasnext () to check if there are elements in the sequence.
(4) use remove () to delete the newly returned element of the iterator.
Just take a look at the following example:
Import java.util.*;p Ublic class Muster {public static void main (string[] args) {ArrayList list = new ArrayList (); List.add ( "a"); List.add ("B"); List.add ("C"); Iterator it = List.iterator (); while (It.hasnext ()) {String str = (string) it.next (); System.out.println (str);}}}
Operation Result:
A
B
C
As you can see, iterator can traverse the entire list through next () without having to control how the underlying data is stored.
But how is it implemented? What is the mechanism behind it?
Here we look at the source code of Java abstractlist implementation iterator :
1.public abstract class Abstractlist<e> extends abstractcollection<e> implements list<e> {// The list interface implements the Collection<e>, iterable<e> 2. 3. Protected Abstractlist () {4. } 5. 6 ..... 7.8. Public iterator<e> Iterator () {9. return new Itr (); This returns an iterator 10. } 11. Private class Itr implements Iterator<e> {//inner class Itr implement iterator 13. int cursor = 0; Lastret int =-1; Expectedmodcount int = Modcount; 17.18. public Boolean Hasnext () {///implement Hasnext method 19. return cursor! = size (); 20.} 21. Public E Next () {//implement Next method 23. Checkforcomodification (); try {25. E next = get (cursor); Lastret = cursor++; return next; The.} catch (Indexoutofboundsexception e) {29. Checkforcomodification (); A. throw new Nosuchelementexception (); 31.} 32. } 33. public void Remove () {//implement REMove method 35. if (Lastret = =-1) 36. throw new IllegalStateException (); Panax Notoginseng checkforcomodification (); 38.39. try {40. AbstractList.this.remove (Lastret); 42. If (Lastret < cursor). cursor--; Lastret =-1; Expectedmodcount = Modcount; A.} catch (Indexoutofboundsexception e) {46. throw new Concurrentmodificationexception (); 47.} 48. } 49. final void Checkforcomodification () {51. if (modcount! = Expectedmodcount) 52. throw new Concurrentmodificationexception (); 53.} 54. } 55.}
As you can see, implementing Next () is through get (cursor), and then cursor++, through this implementation traversal.
This part of the code is not ugly to understand, the only difficult to understand is the remove operation involved in the expectedmodcount = Modcount;
It's on the internet that this is a " quick fail " mechanism in a set iteration that provides security for the collection during the iteration.
from the source code can see additions and deletions will make modcount++, through and expectedmodcount contrast, the iterator can quickly know whether there are list.add () similar operations in the iterative process, the existence of rapid failure! in a practical example:
Import java.util.*;p Ublic class Muster {public static void main (string[] args) {ArrayList list = new ArrayList (); List.add ( "a"); List.add ("B"); List.add ("C"); Iterator it = List.iterator (); while (It.hasnext ()) {String str = (string) it.next (); System.out.println (str); List.add ("S");}}
Operation Result:
A
Exception in thread "main" java.util.ConcurrentModificationException
At Java.util.arraylist$itr.checkforcomodification (Unknown Source)
At Java.util.arraylist$itr.next (Unknown Source)
At Com.hasse.Muster.main (muster.java:11)
this throws one of the following exceptions, and the iteration terminates. for
Modcount, the API is explained as follows:The number of times this list has been structurally modified. Structural Modifications is those the the size of the list, or otherwise perturb it in such a fashion th At iterations in progress may yield incorrect results. that is, Modcount records the number of times this list has been modified: including changing the structure of the
list, changing the size of the list, disrupting the order of the list , and so on, causing errors in the iteration. Tips: Simply setting the value of an element is not a modification of the structureWhat we know is that ArrayList is thread insecure, and if there are other threads modifying the list in the process of using iterators , it throws Concurrentmodificationexception, which is
Fail-fast mechanism.
The use of iterator (iterator) in Java and the mechanism behind it