Java Data Structure Learning-Iterator Interface

Source: Internet
Author: User

Java Data Structure Learning-Iterator Interface

An iterator is an object that can be an element in our iteration set.

In Java Collection APIs, The Iterator interface is small and contains only three methods:

1. boolean hasNext ()

If there are items for iterative browsing in this iteration, true is returned.

2. AnyType next ()

Return the reference to the next object not seen by this iterator. If the object becomes visible, the iterator moves back.

3. void remove ()

This method can be used only once before next is called.

Each set defines the implementation of its own Iterator interface.

For the user, this implementation is in an invisible class.

Example: Based on the inherited iterator and factory Method

Package com. demo. hephec;

Public class MyContainer {

Obeject [] items;

Int size;

Public Iterator iterator (){

Return new MyContainerInterator (this );

}

// Othre method not shown.

}

// Interface Interator

Package com. demo. hephec;

Public interface Interator {

Boolean hasNext ();

Object next ();

}

// The iterator class that implements the interface

Package com. demo. hephec;

Class MyContainerInterator implements Interator {

Private current int = 0;

Private MyContainer container;

MyContainerInterator (MyContainer c ){

Container = c;

}

Public boolean hasNext (){

Return current

}

Public Object next (){

Container, items [currrent ++];

}

}

// Main method

Public static void main (String [] args ){

MyContainer container = new MyContainer ();

Container. add ("3 ");

Container. add ("5 ");

System. out. println ("Container content :"):

Interator itr = container. interator ();

While (itr. hasNext ()){

System. out. println (itr. next ());

}

}

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.