Java Source Code Analysis: In-depth discussion of iterator mode

Source: Internet
Author: User

Java Source Code Analysis: In-depth discussion of iterator mode

Brother Lian

The Java.util package contains a series of important collection classes. This article will start from the analysis of source code, in-depth study of the internal structure of a collection class, as well as iterating over the collection of iterative mode of the source code implementation inside.

let's start with a brief discussion of a root interface Collection, and then analyze an abstract class abstractlist and its corresponding iterator interface, and carefully study the implementation of the iterative sub-mode principle.

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, in order to simplify the problem, we still discuss the 1.4 version of the code.

the root interface of the collection class 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, but the return value does not indicate whether the addition succeeds or not. Read DOC carefully to see that collection rules: If a collection refuses to add this element, it must throw an exception for whatever reason. The meaning of this return value is that when the Add () method executes, the contents of the collection change (that is, the element has no quantity, position, etc.), which is implemented by the concrete class. That is, if the method is faulted, an exception is always thrown, and the return value simply indicates that the content of the collection has changed after the execution of the method.

similar to the following:

Boolean AddAll (Collection c);

Boolean remove (Object O);

Boolean RemoveAll (Collection c);

Boolean remainall (Collection c);

Object[] The ToArray () method is simple and returns the set conversion array. Object[] ToArray (object[] A) The method is a little more complicated, first, the returned object[] is still an array of all the elements of the collection, but the type and parameter A are the same type, such as execution:

string[] o = (string[]) C.toarray (new string[0]);

the actual type of O obtained is string[].

Second, if the size of the parameter A does not fit all the elements of the collection, the returned array will be a new one. If the size of parameter a can fit all the elements of the collection, the return is still a, but the contents of a are populated with the elements of the collection. It is especially important to note that if a is larger than the number of collection elements, the part after a is all set to NULL.

The last most important method is iterator (), which returns a iterator (iteration child) that iterates through all the elements of the collection.

with Iterator Pattern Implementation Traversal collection

The iterator pattern is the standard access method used to traverse the collection class. It abstracts the access logic from different types of collection classes, thus avoiding exposing the internal structure of the collection to the client.

For example, if you do not use Iterator, the way to iterate through an array is to use an index:

for (int i=0; i

while accessing a linked list ( LinkedList) must also use the while loop:

while ((E=e.next ())!=null) {... e.data () ...}

Both methods the client must know in advance the internal structure of the collection, the Access code and the collection itself is tightly coupled, unable to separate the access logic from the collection class and client code, each collection corresponding to a traversal method, the client code can not be reused.

more frightening is that if you need to ArrayList replaced with LinkedList, the original client code must all be rewritten.

to solve the above problems, The iterator pattern always uses the same logic to iterate through the collection:

for (Iterator it = C.iterater (); It.hasnext ();) { ... }

The secret is that the client itself does not maintain a "pointer" that iterates through the collection, and that all internal states (such as the current element's position and whether there is a next element) are maintained by iterator, and this iterator is generated by a factory method of the collection class, so it knows how to traverse the entire collection.

the client never deals directly with the collection class, it always controls Iterator, send it a "forward", "backward", "take the current Element" command, you can indirectly traverse the entire collection.

First look at the definition of the Java.util.Iterator interface:

Public interface Iterator {

Boolean hasnext ();

Object next ();

void Remove ();

}

depending on the first two methods you can complete the traversal, the typical code is as follows:

for (Iterator it = C.iterator (); It.hasnext ();) {

Object o = It.next ();

Operation on o ...

}

in the In JDK1.5, the syntax of the above code is also simplified:

The type is specific, such as String.

for (Type t:c) {

Operation on t ...

}

Each collection class returns the Iterator specific types may differ, the array may return Arrayiterator,set may return Setiterator,tree may return treeiterator, but they all implement the iterator interface, so The client doesn't care what kind of iterator it is, it just needs to get the iterator interface, which is the power of object-oriented.

Iterator Source Code Analysis

Let's take a look at Abstracylist how to create iterator. First Abstractlist defines an inner class (inner class):

Private class Itr implements Iterator {

...

}

The iterator () method is defined as:

Public Iterator Iterator () {

return new Itr ();

}


Java Source Code Analysis: In-depth discussion of iterator mode

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.