Implementation method of Java set iterator iteration _java

Source: Internet
Author: User
Tags concurrentmodificationexception

We often use the iterative interface provided by JDK to iterate over the Java collection.

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

iterations, in fact, we can simply understand that traversal is a standardized method for traversing all the objects within a container, which is a typical design pattern. The iterator pattern is the standard access method used to traverse collection classes. It can abstract the access logic from different types of collection classes, thereby avoiding exposing the internal structure of the collection to the client. We do this in the absence of iterators. As follows:

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 how it is handled:

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

In both ways, we always know the internal structure of the collection in advance, and the access code and the collection itself are tightly coupled, unable to separate the access logic from the collection class and the client code. At the same time, each set corresponds to a traversal method, and client code cannot be reused. It is quite troublesome to use the two sets of the above to consolidate in practical applications. So in order to solve the above problem, iterator mode is born, it always uses the same logic to traverse the collection. So that the client itself does not need to maintain the internal structure of the collection, all the internal state is maintained by iterator. The client never deals directly with the collection class, it always controls the iterator, sends it forward, "backwards", and "takes the current element" to traverse the entire collection indirectly.

It's just a simple description of the iterator pattern, so let's look at the iterator interface in Java to see how it's done.

First, Java.util.Iterator

Iterator in Java is an interface that provides only the basic rules of iteration, as defined in the JDK: an iterator that iterates over collection. The iterator replaces the enumeration in the Java collections Framework. An iterator differs from an enumeration by two points:

1, the iterator allows the caller to use well-defined semantics to remove elements from the collection that the iterator points to during the iteration.

2, the method name has been improved.

The interface is defined as follows:

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

which

Object Next (): Returns a reference to the element that the iterator just crossed, the return value is Object, and needs to be cast to the type that you want

Boolean Hasnext (): Determine if there are any elements in the container that are accessible

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

For us, we only generally need to use next (), Hasnext () Two methods to complete the iteration. As follows:

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

Iterator has a great advantage, that is, we do not need to know the internal results of the collection, the internal structure of the set, the state is maintained by the iterator, through a unified approach Hasnext (), Next () to determine, get the next element, As for the specific internal implementation, we don't have to care. But as a qualified programmer, it is very necessary for us to understand the implementation of iterator. The following is the source of ArrayList analysis and analysis.

The realization of the iterator of each set

The following on the implementation of the ArrayList iterator analysis, in fact, if we understand the ArrayList, HashSet, TREESET data structure, internal implementation, for them how to achieve iterator will also be confident. Because the internal implementation of ArrayList is an array, so we only need to record the index of the corresponding location, the implementation of the method is relatively simple.

2.1, the iterator realization of ArrayList

Inside the ArrayList is the first definition of an internal class Itr, which implements the iterator interface, as follows:

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 now we need to be concerned with the implementation of the ITR () inner class:

Three int variables are defined within the 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 less than cursor one so hasnext () Implementation method is very simple, just to determine whether cursor and lastret are equal.

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

For next () implementation is also relatively simple, as long as the return cursor index location of the elements can then modify cursor, Lastret can

Public E Next () {
checkforcomodification ();
int i = cursor; Record index position if
(i >= size)//If the get element is greater than the number of collection elements, throw an 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 back to cursor element
}

Checkforcomodification () is mainly used to determine whether the number of changes in the collection is legitimate, that is, to determine whether the collection has been modified during the traversal. Modcount is used to record the number of changes to the ArrayList set, initialized to 0, whenever the set is modified (structure above, internal update does not count), such as add, remove and other methods, Modcount + 1, so if modcount unchanged, Indicates that the contents of the collection have not been modified. This mechanism is mainly used to implement the fast failure mechanism of the ArrayList set, in the Java collection, the larger part of the collection is a fast failure mechanism, here is not much to say, later will be mentioned. So to ensure that there is no error in the traversal process, we should ensure that in the traversal process will not produce structural changes (except for the Remove method), there is an abnormal error, we should carefully check whether the program error, not catch after not do processing.

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

For the Remove () method is implemented, it is the Remove () method that calls the ArrayList itself to delete the Lastret position element, and then modify 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 ();
}
}

The above is a small series to introduce the Java set iterator iterative implementation method, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.