Iterator Pattern)

Source: Internet
Author: User

1. What is the iterator mode?

The iterator is used to encapsulate the traversal details of the Set object, so that the caller can traverse the set through a unified interface.

The iterator also provides some protection for the set object. to traverse the set, you just need to call the iterator method directly. We do not know or need to know the data management method in the set.

Ii. Example

Assuming that there is a set of custom objects, we do not know which set objects they are used for maintenance, which may be array, list, or others. Our job is to traverse this set of objects (or add some additional processing on the basis of traversal)

Think about how we can implement it?

First, judge the type of the Set object, and then perform different processing

For each set type, we need a different loop for processing. Although these loop blocks have only slight differences, we have to provide a loop for processing.

.. If there are 100 different collection types, we may have to use 100 loops that are similar to each other to achieve traversal. There is no doubt that there is a large amount of redundant code.

Therefore, we need a unified entrance to turn N cycles into an adaptive loop.

So the iterator is the unified entry we are thinking about:

Iterator Interface

Package iteratorpattern; /*** @ author ayqy * defines the iterator */public interface iterator {/*** @ return indicates whether the next element exists in the Set */Public Abstract Boolean hasnext (); /*** @ return returns the next element in the Set */public abstract object next ();}

You also need to implement some specific iterators to traverse the details:

Array iterator:

Package iteratorpattern;/*** @ author ayqy * implement array iterator */public class arrayiterator implements iterator {myobject [] arr; // int index of the custom object array = 0; // The current index public arrayiterator (myobject [] ARR) {This. arr = arr ;}@ overridepublic Boolean hasnext () {If (index <arr. length & arr [Index]! = NULL) return true; return false ;}@ overridepublic object next () {myobject mo = arr [Index]; index ++; return Mo ;}}

P.s. Pay attention to the specific implementation of the hasnext method of the array iterator.

List iterator:

Package iteratorpattern; import Java. util. list;/*** @ author ayqy * implement list iterator */public class listiterator implements iterator {list <myobject> list; // set object int Index = 0; // The current index public listiterator (list <myobject> List) {This. list = List ;}@ overridepublic Boolean hasnext () {If (index <list. size () return true; return false;} @ overridepublic object next () {myobject mo = List. get (INDEX); index ++; return Mo ;}}

With these specific iterators, we only need a loop to get it done:

/*** Print all content in the Set * @ Param ITER set iterator */Private Static void printobjs (iterator ITER) {While (ITER. hasnext () {system. out. println (ITER. next (). tostring ());}}

Iii. Java's support for iterator

Due to the convenience and necessity of the iterator, iterator is supported after java. Currently, many collection objects support iterator, such as set, list, MAP, sortedset, sortedmap, hashset, treeset, arraylist, struct list, vector, etc.

The only thing that does not support the iterator is the Array (except stack and queue). We have implemented the custom iterator interface above. In fact, Java itself provides this interface (Java. util. iterator), but the difference is:

The Java. util. iterator interface defines three methods (except the hasnext and next methods, there are also the remove methods ):

It doesn't matter if the collection object is unwilling to provide the remove method. We can throw an exception to reject the implementation, just like this:

Package iteratorpattern;/*** @ author ayqy * use the iterator interface provided by Java to implement the array iterator */public class javaarrayiterator implements Java. util. iterator {myobject [] arr; // custom object array int Index = 0; // The current index public javaarrayiterator (myobject [] ARR) {This. arr = arr ;}@ overridepublic Boolean hasnext () {If (index <arr. length & arr [Index]! = NULL) return true; return false ;}@ overridepublic object next () {myobject mo = arr [Index]; index ++; return Mo ;}@ overridepublic void remove () {// throw operation does not support exception throw new unsupportedoperationexception ();}}

The method of calling the iterator has not changed at all:

/*** Print all content in the Set * @ Param ITER set iterator */Private Static void printobjs (Java. util. iterator ITER) {While (ITER. hasnext () {system. out. println (ITER. next (). tostring ());}}

Iv. implicit call of the iterator

Many languages support the for each (or for in) loop. The internal implementation is to call the iterator to complete the traversal.

Of course, it's just a little bit of common sense. More importantly, you can learn the design principles of the iterator and define your own iterator as needed.

5. Expansion

The iterator mode itself is relatively simple, and we don't even need to define our own iterator (the iterator interface provided by the API can almost meet our needs)

However, when the iterator is combined with the combination mode, you can do some incredible things (for details in the combination mode, click "I jump">)

Iterator Pattern)

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.