Java source code analysis: iterator

Source: Internet
Author: User
Tags concurrentmodificationexception
Run: For (iterator it = O. getsons (). iterator (); it. hasnext ();){
R = (knowledgenode) it. Next ();
It. Remove (); // if it is changed to O. getsons (). Remove (r);, the concurrentmodificationexception will be thrown.
} An exception occurred. It turned out to be an iterator synchronization problem. The Remove Method of the set used for calling. It is best to use the iterator method. For example, it is no problem to delete the current element using the remove () method of iterator itself. -------------------------------------------------------------------------------- The java. util package contains a series of important collection classes. This article will start with analyzing the source code, thoroughly studying the internal structure of a collection class, and traversing the source code implementation of the iteration mode of the set.

Next, we will briefly discuss a Root Interface collection, analyze a abstract class abstractlist and its corresponding iterator interface, and carefully study the implementation principle of the iteration submode.

The source code version discussed in this article is JDK 1.4.2, because JDK 1.5 uses a lot of generic code in Java. util. to simplify the problem, we still discuss the code of version 1.4.

  Collection

The collection interface is the root type of all collection classes. One of its main interface methods is:

Boolean add (Object C)


The add () method adds a new element. Note that this method returns a Boolean value, but the returned value does not indicate that the value is successfully added. Read the doc carefully and you can see that collection rules: If a collection refuses to add this element, an exception must be thrown for any reason. The returned value indicates whether the content of the set has changed after the add () method is executed (that is, whether the number and position of the element have changed), which is implemented by a specific class. That is, if a method error occurs, an exception is always thrown. The returned value only indicates whether the content of the collection changes after the method is executed.

Similar:

Boolean addall (collection C );
Boolean remove (Object O );
Boolean removeall (collection C );
Boolean remainall (collection C );


The object [] toarray () method is very simple. Convert the set into an array and return it. The object [] toarray (object [] A) method is a bit complicated. First, the returned object [] Still converts all elements of the set into an array, but the type is the same as the type of parameter A, for example, run:

String [] O = (string []) C. toarray (New String [0]);


The actual O type is string [].

Second, if the size of parameter A does not fit all the elements in the Set, a new array is returned. If the size of parameter A can hold all the elements of the set, the returned result is A, but the content of A is filled with the elements of the set. In particular, if the size of a is more than the number of elements in the Set, all parts after a are set to null.

The last and most important method is iterator (), which returns an iterator (iterator) to traverse all elements of the set.

  Traverse a set in iterator Mode
 
The iterator mode is a standard access method used to traverse collection classes. It can abstract the access logic from a collection class of the same type to avoid exposing the internal structure of the set to the client.

For example, if the iterator is not used, the index is used to traverse an array:

For (INT I = 0; I <array. Size (); I ++) {... get (I )...}


To access a linked list, you must use the while loop:

While (E = E. Next ())! = NULL) {... e. Data ()...}


The clients of the above two methods must know the internal structure of the set in advance. The access code and the set itself are tightly coupled and the access logic cannot be separated from the Collection class and client code, each set corresponds to a Traversal method, and client code cannot be reused.

What's even more frightening is that if you need to replace arraylist with a future list, all the original client code must be rewritten.

To solve the above problem, the iterator mode always uses the same logic to traverse the set:

For (iterator it = C. iterater (); it. hasnext ();){...}


The mystery is that the client does not maintain the "Pointer" of the traversal set. All internal states (such as the current element location and whether there is any next element) are maintained by iterator, this iterator is generated by the collection class through the factory method, so it knows how to traverse the entire set.

The client never directly deals with the collection class. It always controls the iterator and sends the "forward", "backward", "Get current element" command to it to indirectly traverse the entire set.

First, let's take a look at the definition of the Java. util. iterator interface:

Public interface iterator {
Boolean hasnext ();
Object next ();
Void remove ();
}


The traversal can be completed by relying on the first two methods. The typical code is as follows:

For (iterator it = C. iterator (); it. hasnext ();){
Object o = it. Next ();
// O operations...
}


In jdk1.5, the above Code is also simplified in syntax:

// Type is a specific type, such as string.
For (type T: C ){
// T operation...
}


The iterator types returned by each collection class may be different. array may return arrayiterator, set may return setiterator, and tree may return treeiterator, but they all implement the iterator interface. Therefore, the client does not care about which iterator it is. It only needs to obtain this iterator interface, which is the power of object-oriented.
Let's take a look at how abstracylist creates an iterator. First, abstractlist defines an inner class ):

Private class itr implements iterator {
...
}

The iterator () method is defined as follows:

Public iterator (){
Return new itr ();
}

Therefore, the client does not know the real type of iterator obtained through iterator it = A. iterator.

Now we are concerned about how the private itr class traverses javasactlist:

Private class itr implements iterator {
Int cursor = 0;
Int lastret =-1;
Int expectedmodcount = modcount;
}

The itr class traverses three int variables (and an implicit abstractlist reference). The cursor is the position of the element in the next () call and calls next () for the first time () returns the element with an index of 0. Lastret records the position of the last cursor, so it is always 1 less than cursor.

The number of elements in the variable cursor and set determines hasnext ():

Public Boolean hasnext (){
Return cursor! = Size ();
}

The method next () returns the element whose index is cursor, and then modifies the values of cursor and lastret:

Public object next (){
Checkforcomodification ();
Try {
Object next = get (cursor );
Lastret = cursor ++;
Return next;
} Catch (indexoutofboundsexception e ){
Checkforcomodification ();
Throw new nosuchelementexception ();
}
}

Expectedmodcount indicates the expected modcount value, which is used to determine whether the combination has been modified during the traversal process. Abstractlist contains a modcount variable whose initial value is 0. When the set is modified once (the add, remove, and other methods are called), modcount is added to 1. Therefore, if modcount remains unchanged, the set content is not modified.

When itr is initialized, expectedmodcount is used to record the modcount variable of the set. It then detects the value of modcount where necessary:

Final void checkforcomodification (){
If (modcount! = Expectedmodcount)
Throw new concurrentmodificationexception ();
}

If modcount is different from the value of the initial record in expectedmodecount, it indicates that the set content has been modified and concurrentmodificationexception is thrown.

This concurrentmodificationexception is runtimeexception and should not be captured on the client. If this exception occurs, it indicates that there is a problem with programming code. You should check the code carefully instead of ignoring it in catch.

However, it is no problem to call the remove () method of iterator to delete the current element, because the expectedmodcount and modcount values are automatically synchronized in this method:

Public void remove (){
...
Abstractlist. This. Remove (lastret );
...
// After the remove () method of the set is called, The expectedmodcount is reset:
Expectedmodcount = modcount;
...
}

To ensure the smooth completion of the traversal process, you must ensure that the content of the set is not changed during the traversal process (except for the remove () method of iterator). Therefore, to ensure reliable traversal, you can only use this set in one thread or synchronize the traversal code in multiple threads.

Finally, a complete example is provided:

Collection c = new arraylist ();
C. Add ("ABC ");
C. Add ("XYZ ");
For (iterator it = C. iterator (); it. hasnext ();){
String S = (string) it. Next ();
System. Out. println (s );
}

If you replace the arraylist of the first line of code with a struct list or vector, the remaining code can be compiled without changing the line, and the function remains unchanged. This is the principle of abstract programming: the minimum dependence on a specific class.

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.