Iterator mode in java Collection class

Source: Internet
Author: User

Iterator mode in java Collection class

For more information about the mode, see the example in <Zen of design mode>.
The boss needs to see the various projects in the company. (I know that my overview is very impressive. Check the code)
Sample Code v1

Package Iterator;/**** @ author cbf4Life cbf4life@126.com * defines an interface, all projects are an interface */public interface IProject {// from the boss, the project information is public String getProjectInfo ();} package Iterator; /*** @ author cbf4Life cbf4life@126.com * Information class for all projects */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, store all the information that the boss needs to see. public Project (String name, int num, int cost) {// assign a value to the member variable of the class. this. name = name; this. num = num; this. cost = cost;} // obtain the project information public String getProjectInfo () {String info =; // obtain the project name info = info + the project name is + this. name; // obtain project count info = info + project count: + this. num; // project fee info = info + project fee: + this. cost; return info ;}} package Iterator; import java. util. arrayList;/*** @ author cbf4Life cbf4life@126.com * The Boss looked at the project information */public class Boss {public static void main (String [] args) {// defines a List, store all project objects in ArrayList
 
  
ProjectList = new ArrayList
  
   
(); // Add the Star Wars project projectList. add (new Project (Star Wars Project, 10, 10); // add a Project to reverse the time space. add (new Project (reverse space-time Project,); // add a superman transformation Project projectList. add (new Project (Superman transformation Project, 100,); // projects for (int I = 4; I <10; I ++) projectList. add (new Project (+ I + project, I * 5, I * 100); // traverse the ArrayList and retrieve all the data for (IProject Project: projectList) System. out. println (project. getProjectInfo ());}}
  
 


The class diagram is as follows:

It's too simple to say.
But now I want to raise a few questions.
The aggregation of multiple objects is called Aggregate ). In java, these classes implement the Collection interface. The arrays we came into contact with when learning c are the most basic aggregation. in java, arrays are also the basis for designing other clustering types.
Java 1.2 has provided a variety of clustering functions, such as Vector, ArrayList, Stack, LinkList, HashSet, TreeSet, HashMap, and TreeMap.
Arrays, stacks, and HASH lists have multiple storage structures. If I don't want an array to store project information and want to replace it with a hash, the above Code will be greatly changed (in fact, I have to admit that there is a problem with this assumption. Few people will be idle and have to worry about changing the storage structure. Let's just give an example to introduce the question below)
We hope that various clustering in java can provide an iterative function.
OK. Check our next version.


As you can see, we have used the iterator-related modules provided by jdk.
V2
public interface Iterable
 
   {    Iterator
  
    iterator();}
  
 
Iterable interface, which must be implemented by any aggregation with iteration functions. It also has only one method to return the aggregation iterator.

public interface Iterator
 
   {    boolean hasNext();    E next();    void remove();}
 
The Iterator interface is a specific Iterator.
When you understand the iterator mode, you may think that a clustering can traverse itself, because we use the for loop to retrieve each element in sequence. Now, after the pattern is introduced, the traversal function is handed over to the iterator class (interface.
View code now

Package iterator. v2; import java. util. ArrayList; import java. util. Iterator;/*** @ author cbf4Life cbf4life@126.com * defines an Iterator */public class ProjectIterator implements iterator{// All projects are placed in the ArrayList private ArrayList.
  
   
ProjectList = new ArrayList
   
    
(); Private int currentItem = 0; // constructor Entry and Exit projectList public ProjectIterator (ArrayList
    
     
ProjectList) {this. projectList = projectList;} // 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;} // obtain the next value public IProject next () {return (IProject) this. projectList. get (this. currentItem ++);} // delete an object public void remove () {// not used yet} package iterator. v2; import java. util. iterator;/*** @ author cbf4Life cbf4life@126.com * defines an interface, and all projects are an interface */public interface IProject extends Iterable
     {// Add the Project public void add (String name, int num, int cost); // you can see the project information public String getProjectInfo (); public IteratorIterator ();} package iterator. v2; import java. util. arrayList; import java. util. iterator;/*** @ author cbf4Life cbf4life@126.com * Information class for all projects */@ SuppressWarnings (all) public class Project implements IProject {// define a Project list, some projects are put here private ArrayList
       
         ProjectList = new ArrayList
        
          (); // Project name private String name =; // number of Project members private int num = 0; // Project fee private int cost = 0; public Project () {} // define a constructor to store all the information that the boss needs to see in 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);} // obtain the Project information public String getProjectInfo (){...} // generate a traversal object public Iterator
         Iterator () {return new ProjectIterator (this. projectList) ;}} package iterator. v2;/*** @ author cbf4Life cbf4life@126.com * The Boss looked at the project information */public class Boss {public static void main (String [] args) {// defines a List, save all project objects IProject Project = new project (); // Add a Star Wars project. add (Star Wars project ddddd, 10,100); // add a project to reverse the time space project. add (reverse time and space project,); // add a superman transformation project. add (Superman transformation project, supervisor, supervisor 00); // 100 projects for (int I = 4; I <14; I ++) {project. add (the + I + project, I * 5, I * 1000);} // traverse the ArrayList and retrieve all the data from ProjectIterator projectIterator = (ProjectIterator) project. iterator (); while (projectIterator. hasNext () {IProject p = (IProject) projectIterator. next (); System. out. println (p. getProjectInfo ());}}}
        
       
    
   
  


Generic class diagram of the iterator Mode


The relationship between the specific iterator and the specific aggregation is a bit interesting. I hope you can take a look at the code.
On the other hand, we can place ProjectIterator as an internal class in the projcet class so that the iterator can directly access projectList.
Later, we changed it and then added it to the boss class.
ProjectIterator projectIterator = (ProjectIterator) project. iterator ();
Code can still be used. This is the benefit of separation between creation and use, that is, the benefit of the factory model.

Application of jdk iterator mode in clustering

Uml diagram


There are two methods in AbstractList:
    public ListIterator
 
   listIterator() {        return new ListItr(0);    }     public Iterator
  
    iterator() {        return new Itr();    }
  
 

No matter the above uml diagram or the following code, you must have a question in your mind. What is the problem between ListItr and Itr.

In fact, we only need to look at the source code of AbstractList to understand that there are too few methods in the Iterator interface. hasNext, next, and remove are three methods. In traversal, this is positive traversal, what if I want to reverse traverse it? This function is available in ListItr.
Next, let's look at the Code:
Import java. util. *; public 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 (Dragon girl); process (persons );}}


Now we use ArrayList to store data. If we want to replace it with HashSet
Persons = new HashSet (); // Create an aggregate object of the ArrayList type
A line of code.

 

Related Article

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.