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 ());
}
}