Java Improvement (30)-----Iterator

Source: Internet
Author: User
Tags concurrentmodificationexception

iterations are definitely not unfamiliar to us in Java. We use the iterative interface provided by the JDK to iterate over the Java collection.

Iterator Iterator = List.iterator ();        while (Iterator.hasnext ()) {            String string = Iterator.next ();            Do something        }

In fact, we can simply understand the iteration as a traversal. is a method class that standardizes all the objects inside all kinds of containers, which is a very typical design pattern. 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. This is what we do when there are no iterators. For example, the following:

for Arrays we use subscripts for processing:

int[] Arrays = new Int[10];for (int i = 0; i < arrays.length; i++) {       int a = arrays[i];       Do something   }

for ArrayList, this is handled:

list<string> list = new arraylist<string> ();   for (int i = 0; i < list.size ();  i++) {      string string = List.get (i);      Do something   }

for both of these ways. We always know the internal structure of the collection beforehand, and the access code and the collection itself are tightly coupled, and the access logic cannot be detached from the collection class and the client code. At the same time, each collection has a corresponding traversal method, and the client code cannot be reused. The need to integrate the two sets above is cumbersome in practical applications.

So in order to solve the above problem, iterator mode vacated, it always use the same logic to traverse the collection. So that the client itself does not need to maintain the internal structure of the collection. All internal states are maintained by the iterator.

The client never deals directly with the collection class, it always controls the iterator and sends it forward. "Back", "Fetch current Element" command. It is possible to traverse the entire collection indirectly.

above is just a simple description of the iterator mode, let's look at the Java iterator interface, see how he came to implement.

First, Java.util.Iterator

iterator is an interface in Java. It simply provides an iterative basic rule, which he defines in the JDK: an iterator that iterates over the collection.

Iterators replace the enumeration in the Java collections Framework. Iterators are two points different from enumerations:

1. The iterator agrees that the caller removes the element from the collection pointed to by the iterator during the iteration, using well-defined semantics.

2, the method name has been improved.

its interface definitions such as the following:

Public interface Iterator {Boolean hasnext ();  Object next (); void Remove ();

among them:

Object Next (): Returns the reference to the element that the iterator has just crossed, and the return value is Object, which must be converted to its own type.

Boolean hasnext (): Infer if there are any accessible elements within the container

void Remove (): Delete the element that the iterator just crossed

for us. We only generally need to use next (), Hasnext () Two methods to complete the iteration. For example, the following:

for (Iterator it = C.iterator (); It.hasnext ();)   {Object o = It.next (); Do something}

iterator has a very big advantage, that is, we do not have to know the internal results of the collection, the internal structure of the set, the state is maintained by the iterator, through a unified method Hasnext (), next () to infer, get the next element, As for the detailed internal implementation, we don't have to worry about it.

but as a qualified program ape we are very much obliged to clarify the realization of iterator. The following is the ArrayList source code for analysis and analysis.

realization of the iterator of each set

The following is an analysis of the iterator implementation of ArrayList, in fact assuming that we understand the ArrayList, Hashset, TREESET data structure, internal implementation, and how they implement iterator will be confident. Because of the internal implementation of the ArrayList array. So we just need to record the index of the corresponding position can be, its method of implementation is relatively simple.

2.1, the iterator realization of ArrayList

inside ArrayList is the first definition of an inner class ITR, which implements the iterator interface, such as the following:

Private class Itr implements iterator<e> {    //do something}

and ArrayList's iterator () method implements:

Public iterator<e> Iterator () {        return new Itr ();    }

so the ITR () inner class is returned by using the Arraylist.iterator () method. So what we need to worry about now is the implementation of the ITR () inner class:

Three variables of type int are defined within ITR: Cursor, Lastret, Expectedmodcount. where cursor represents the index position of the next element, Lastret represents the index position of the previous element

int cursor;             int lastret =-1;     int expectedmodcount = Modcount;

from the cursor, Lastret definition can be seen. Lastret has been a little less than the cursor so the Hasnext () Implementation method is surprisingly simple, just need to infer whether the cursor and lastret are equal.

public Boolean Hasnext () {    return cursor! = size;}

the next () implementation is actually simpler. Just return the element at the cursor index position, then change the cursor, Lastret,

Public E Next () {            checkforcomodification ();            int i = cursor;    Record index position            if (i >= size)    //Assume that the fetch element is greater than the number of collection elements. Throws the exception                throw new Nosuchelementexception ();            object[] Elementdata = ArrayList.this.elementData;            if (i >= elementdata.length)                throw new Concurrentmodificationexception ();            cursor = i + 1;      Cursor + 1            return (E) Elementdata[lastret = i];  Lastret + 1 and returns the cursor at the element        }

checkforcomodification () is used primarily to infer whether the number of changes to a collection is legitimate, that is, to infer whether the collection has been altered during traversal. In the Java Improvement Chapter (21)-----ArrayList has been elaborated. Modcount is used to record the number of changes to the ArrayList collection, initialized to 0, whenever the collection is changed (structure above changes. Internal update does not count), such as Add, remove, and so on, Modcount + 1, so assume that modcount unchanged, it means that the contents of the collection has not been changed.

This mechanism is mainly used to implement the high-speed failure mechanism of ArrayList set. In the Java collection, a large subset of the collection is a high-speed failure mechanism, and here is not much to say. I'll talk about it later. So to ensure that there are no errors in the traversal process, we should ensure that the collection is not structurally altered during the traversal (except of course the Remove method). In the event of an unexpected error, we should carefully check the program for errors rather than after the catch.

       final void Checkforcomodification () {            if (modcount! = expectedmodcount)                throw new Concurrentmodificationexception ();        }

for the Remove () method, it is an implementation that calls the Remove () method of the ArrayList itself to delete the Lastret position element. Then you can change the modcount.

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 ();            }        }

Here is the solution to the iterator implementation of ArrayList. For HashSet, TreeSet and other sets of iterator implementations, you can continue to study the assumption of interest. Personally, it is necessary to have a clear understanding of the data structure of the collection before studying the source code of these collections. This will achieve a multiplier effect!!!!

—————————————————————————————————————————————————————————
-- Original from:http://cmsblogs.com/?

p=1180.

Respect the results of the author, reproduced please specify the source!



-- personal website:http://cmsblogs.com

Java Improvement (30)-----Iterator

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.