Iterator patterns in the Java collection class

Source: Internet
Author: User
Tags iterable


Do not say the pattern of the problem, look at a << design pattern of Zen >> inside examples.
The boss wants to see the company's various projects. (I know I have a big head look at this overview, see the code.)
Sample Program V1
Package iterator;/** * @author cbf4life [email protected] * Define an interface, all items are an interface */public interface IProject {/    /What you see from the boss is the project information public String getprojectinfo ();    }package iterator;/** * @author cbf4life [email protected] * All items of information class */public class project implements IProject {        Project name Private String name = "";        Number of project members private int num = 0;        Project fee private int cost = 0;        Define a constructor that stores the information that all bosses need to see public Project (String name,int num,int cost) {//assigns a value to the class's member variable this.name = name;        This.num = num;    This.cost=cost;                }//Get information about the project public String Getprojectinfo () {String info = "";        Get the name of the project info = info+ "project name is:" + this.name;        Number of items Received info = info + "\ T Project number:" + this.num;                Project Cost info = info+ "\ T project cost:" + this.cost;    return info; }}package iterator;import java.util.arraylist;/** * @author cbf4life [email protected] * boss to see the project information */public CLass Boss {public static void main (string[] args) {//define a list that holds all the project objects Arraylist<iproje                        ct> projectlist = new arraylist<iproject> ();            Added Star Wars Project Projectlist.add (New project ("Star Wars Project", 10,10));            Added Projectlist.add (New project ("Reverse Space-time project", 100,1000));                        Added Superman makeover Project Projectlist.add (New Project ("Superman Makeover Project", 10000,100000));                            This way 100 items for (int i=4;i<10;i++) Projectlist.add (New Project ("+i+", i*5,i*100)); Walk through the ArrayList and take out all the data for (IProject project:projectlist) System.out.prin        TLN (Project.getprojectinfo ()); }}


The class diagram is as follows:

It's too simple, nothing to say.
But now, I'd like to raise a few questions.
Multiple objects are gathered together to form a population called aggregation (Aggregate). In Java are the classes that implement the collection interface. The array that we touch when we learn C is the most basic aggregation, and in Java, arrays are the basis of the design of other aggregation types.
Starting with version 1.2, Java provides a variety of aggregates, vector,arraylist,stack,linklist,hashset,treeset,hashmap,treemap, and so on.
arrays, stacks, hash lists have a variety of storage structure, if I do not want to have an array to store the project information to be replaced by a hash, the above code will be changed (in fact, I have to admit that the hypothesis itself is problematic, very few people will be free to panic to change the storage structure, we just give an example, lead us to say the
We hope that the various aggregates in Java will provide an "iterative" function.
OK, look at our next version.


As you can see, we have used the iterator-related modules provided by the JDK.
V2
Public interface Iterable<t> {    iterator<t> Iterator ();}
Iterable interface, any aggregation capable of "iterative" functionality implements this interface, and it has only one method that returns a clustered iterator.

Public interface Iterator<e> {    boolean hasnext ();    E next ();    void Remove ();
The iterator interface is the specific iterator.
As you understand the iterator pattern, it's worth thinking that a cluster can traverse itself before because we take each element out of the For loop, and now that the pattern is introduced, the traversal function is passed to the iterator Class (interface).
Now look at the code

Package Iterator.v2;import java.util.arraylist;import java.util.iterator;/** * @author Cbf4life [email protected ] * Define an iterator */public class Projectiterator implements iterator<object>{//All items are placed here ArrayList in private ARR        aylist<iproject> projectlist = new arraylist<iproject> ();        private int currentitem = 0; Constructor Access Projectlist public Projectiterator (arraylist<iproject> projectlist) {this.projectlist = ProjectLis    T        }//To determine if there are still elements, you must implement public Boolean Hasnext () {//define a return value Boolean b = true;        if (this.currentitem>=projectlist.size () | | | this.projectList.get (this.currentitem) = = null) {b =false;    } return B;    }//Get Next Value public IProject next () {return (IProject) this.projectList.get (this.currentitem++); }//Delete an object public void remove () {//temporarily unused to}}package iterator.v2;import java.util.iterator;/** * @author Cbf4life [email protected] * defines aInterface, all items are an interface */public interface IProject extends iterable<object>{//Add Project public void Add (String name,i        NT Num,int cost);            What you see from the boss is the project information public String getprojectinfo (); Public iterator<object> Iterator ();} Package Iterator.v2;import java.util.arraylist;import java.util.iterator;/** * @author Cbf4life [email protected ] * Information class for all items */@SuppressWarnings ("All") public class project implements IProject {//define a list of items, saying that all items are placed here private Arra    ylist<iproject> projectlist = new arraylist<iproject> ();    Project name Private String name = "";    Number of project members private int num = 0;        Project fee private int cost = 0; Public project () {}//defines a constructor that stores the information that all bosses need to see private project (String name,int num,int cost) {.    .     }//Add Project public void Add (String name,int num,int cost) {This.projectList.add (New project (Name,num,cost)); }//Get information about the project public String Getprojectinfo () {...}       Generates a Traverse object public iterator<object> Iterator () {return new projectiterator (this.projectlist);  }}package iterator.v2;/** * @author cbf4life [email protected] * boss to see the project information */public class Boss {public static                        void Main (string[] args) {//define a list that holds all project objects IProject project = new Project ();            Added Star Wars Project Project.add ("Star Wars Project Ddddd", 10,100);            Project.add ("Reverse Time-space project", 100,10000) to increase the torsion time-space project;                        Added Superman makeover Project Project.add ("Superman Makeover Project", 10000,1000000);            This way 100 items for (int i=4;i<14;i++) {project.add ("+i+", "i*5,i*1000"); }//Walk through the ArrayList and take all the data out projectiterator Projectiterator = (projectiterator) project.            Iterator ();                while (Projectiterator.hasnext ()) {IProject p = (IProject) projectiterator.next ();         System.out.println (P.getprojectinfo ());                   }                    }} 


General class diagram of the iterator pattern


The relationship between the specific iterator and the specific aggregation in the figure is a bit of a point, and hopefully we'll look at the code more.
On the other hand, we can also place Projectiterator as an inner class in the Projcet class so that the iterator can access the projectlist directly.
After we change this, then the boss class inside
Projectiterator projectiterator = (projectiterator) project.iterator ();
The code is still available, which is the benefit of creating and using separation, which is the benefit of the factory model.

The application of JDK pattern in aggregation

UML diagram



The following two methods are available in the Abstractlist
    Public listiterator<e> Listiterator () {        return new Listitr (0);    }     Public iterator<e> Iterator () {        return new Itr ();    }

Whether it is the above UML diagram or the following code, we now have a problem in mind, Listitr and ITR is how to go.

In fact, we just have to look at Abstractlist source code can understand: iterator interface inside the method is too little, hasnext,next,remove on three methods, from the traversal to say that is forward traversal, if I want to reverse traverse what to do? Listitr has this function.
Let's look at a piece of code below:
Import java.util.*;p Ublic class Iteratordemo {public   static void process (Collection c) {             Iterator i = c.iterator ( ); Create an Iterator object                 //traverse the aggregation object through an iterator        while (I.hasnext ()) {            System.out.println (I.next ())} ());        }   }    public static void Main (String args[]) {        Collection persons;        persons = new ArrayList (); Create an aggregation object of type ArrayList        persons.add ("Zhang Mowgli");        Persons.add ("Little Dragon Girl");        Persons.add ("Make Fox Punch");        Persons.add ("Wei Xiaobao");        Persons.add ("Yuan Zihua garment");        Persons.add ("Little Dragon Girl");                process (persons);}    }


We are now using ArrayList to store data, if you want to change HashSet is very simple, it will
persons = new hashset<string> (); Create an aggregate object of type ArrayList
One line of code.

Another problem is that a class (class in School) contains multiple students (Student), which uses a Java built-in iterator to traverse the student's information, requiring the student's information to be output in the order of age from large to small.
How to do this, let's discuss it in the next section.
Reference Java and Patterns
The design pattern of the Zen 20th chapter iterator pattern
Http://blog.csdn.net/lovelion/article/details/9992005 iterate through the elements in the aggregation object-the iterator pattern (many of the materials are referenced from Liu Wei's blog)

Iterator patterns in the Java collection 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.