Traverse elements in an aggregate object-iterator mode (5)

Source: Internet
Author: User
5. JDK built-in iterator

To make it easier for developers to operate aggregate objects, a built-in iterator is provided in Java, C #, and other programming languages. In the Java Collection framework, common aggregate classes such as list and set inherit (or implement) the java. util. Collection interface, and the following method (Part) is declared in the collection interface ):

package java.util;public interface Collection<E> extends Iterable<E> {    ……boolean add(Object c);boolean addAll(Collection c);boolean remove(Object o);boolean removeAll(Collection c);boolean remainAll(Collection c); Iterator iterator();……}

In addition to adding and deleting elements, an iterator () method is provided to return an iterator object to traverse the elements in the aggregation; A specific Java aggregation class can return a specific iterator object by implementing the iterator () method.

JDK defines the iterator interface of the abstract iterator. The Code is as follows:

package java.util;public interface Iterator<E> {boolean hasNext();E next();void remove();}

Hasnext () is used to determine whether the next element exists in the aggregate object. To avoid throwing an exception, you must call hasnext () before each call to next (), if an element is accessible, true is returned. The next () method is used to move the cursor to the next element, through which the elements in the aggregation can be accessed one by one, it returns the reference of the element crossed by the cursor. The remove () method is used to delete the element returned when next () is called last time.

Java iterator Working Principle 5 shows that when the first next () method is called, the iterator cursor is moved from element 1 to element 2 to element 3 across element 2, so next () the method returns a reference to element 2. When the second next () method is called, the iterator is moved from "element 2" to "element 3" to "element 3" and "element 4". The next () method returns a reference to "element 3, if you call the remove () method at this time, you can delete "element 3.

 

Figure 5 Java iterator

The following code snippet can be used to delete the first element in an aggregate object:

Iterator = collection. iterator (); // collection is an instantiated aggregate object iterator. next (); // skip the first element iterator. remove (); // Delete the first element

Note that the next () method and the remove () method are associated here. If you do not call next () before you call remove (), an illegalstateexception is thrown because there is no element to delete.

The following code snippet can be used to delete two adjacent elements:

Iterator. Remove (); iterator. Next (); // if you delete this Code Program, an exception occurs. iterator. Remove ();

In the above code snippet, if you remove iterator. Next ();, the program runs an exception, because the elements that can be deleted cannot be found during the second deletion.

In JDK, the collection interface and iterator interface act as the abstraction layer of the iterator mode, which correspond to the abstract aggregation class and the abstract iterator respectively. The subclass of the collection interface acts as the specific aggregation class, the following uses list as an example. Figure 6 lists some list-related classes in JDK and Their Relationships:

Figure6 JavaClassification structure of the central part of the collection framework

(Note: many methods are omitted in this figure to simplify the class diagram)

In JDK, the actual situation is much more complex than figure 6. in figure 6, the list interface inherits the iterator () method of the collection interface, A new factory method listiterator () is added, which is used to create listiterator type iterators. This method is implemented in the listiterator list subclass, the Code is as follows:

public ListIterator<E> listIterator(int index) {return new ListItr(index);}

The listiterator () method is used to return objects of the listitr type of a specific iterator. In the JDK source code, the iterator () method in javasactlist calls the listiterator () method, as shown in the following code:

    public Iterator<E> iterator() {        return listIterator();    }

The client calls the iterator () method of the consumer list class to obtain an iterator object specifically used to traverse the consumer list.

You may ask?Now that we have the iterator () method, why do we need to provide a listiterator () method? Are the functions of these two methods repeated? Why do we need to do that?

This is a good question ,. I will give you a brief explanation of why the design is like this: because there are too few methods defined in the iterator interface, there are only three. Through these three methods, only forward traversal can be implemented, sometimes we need to perform reverse traversal and other operations on an aggregate object. Therefore, the listiterator interface of JDK declares methods such as hasprevious () and previous () used for reverse traversal, if the client needs to call these two methods for reverse traversal, it cannot use the iterator () method to create an iterator, because the iterator object created at this time does not have these two methods. The following code can only be used to create listiterator type iterator objects:

    ListIterator i = c.listIterator();

Because of this, the listiterator () method declaration has to be added to the list interface of JDK. This method can return a listiterator type iterator, And the listiterator iterator has more powerful functions.

Thoughts

Why can't the iterator created using the iterator () method implement reverse traversal?

In Java, we can directly use the built-in JDK iterator to traverse elements in the aggregate object. The following Code demonstrates how to use the built-in JAVA iterator:

Import Java. util. *; Class iteratordemo {public static void process (collection C) {iterator I = C. iterator (); // create an iterator object // use the iterator to traverse the aggregate object while (I. hasnext () {system. out. println (I. next (). tostring () ;}} public static void main (string ARGs []) {collection persons; persons = new arraylist (); // create an aggregate object persons of the arraylist type. add ("Zhang Wuji"); persons. add ("maid"); persons. add ("Ling Hu Chong"); persons. add ("Wei xiaobao"); persons. add ("Yuan Ziyi"); persons. add ("maid"); process (persons );}}

In the static process () method, iterator is used to process the collection object. The running result of this Code is as follows:

Zhang Wuji

Little Dragon girl

Ling huchong

Wei xiaobao

Yuan Ziyi

Little Dragon girl

If you need to change the aggregation type, for example, to change the list to set, you only need to replace the specific aggregation class name. If you change the arraylist in the above Code to hashset, the output result is as follows:

Ling huchong

Zhang Wuji

Wei xiaobao

Little Dragon girl

Yuan Ziyi

Duplicate elements are merged in hashset and output in random order. The result is different from that of arraylist. It can be seen that the use of the iterator mode makes it very convenient to replace a specific aggregation class, and new aggregation classes can be added as needed. The new aggregation class only needs to implement the collection interface, the original class library code does not need to be modified, and the Code complies with the "open and closed principle ".

 

Exercise

In an educational administration system developed by Sunny software company, a class in school contains multiple students and uses the Java built-in iterator to traverse student information, the student information must be output in a descending order of the student's age.

【Author】 Liu WeiHttp://blog.csdn.net/lovelion]

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.