Design Pattern Iterator

Source: Internet
Author: User

Design Pattern Iterator

The iterator design pattern is widely used for traversing in a set.

Internal classes are used here.

The following is a simplified design pattern for an iterator:


1. Iterator Interface

public interface Iterator
 
   {boolean hasNext();E next();}
 

2. Internal class

Public class Outer {private Object [] item; private int size = 0; public Outer (int n) {if (n <= 0) {System. out. println ("out of bounds");} item = new Object [n];} public void add (Object object) {item [size ++] = Object;} public IteratorIterator () {return new Iter ();} public class Iter implements Iterator{Int current = 0; @ Overridepublic boolean hasNext () {return current <size ;}@ Overridepublic Object next () {if (current >=size) {return null ;} return item [current ++] ;}}
3. Test

Public static void main (String [] args) {Outer outer = new Outer (10); outer. add (new Object (); outer. add (new Object (); outer. add (new Object (); outer. add (new Object (); outer. add (new Object (); IteratorIterator = outer. iterator (); while (iterator. hasNext () {System. out. println (iterator. next (). toString ());}}
Output result

java.lang.Object@6ea4b78bjava.lang.Object@51da6868java.lang.Object@1d8806f7java.lang.Object@189ddde9java.lang.Object@1d1d2b8

It is a simple but very usable design model, but the premise is to understand the internal 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.