Java.
You have a hashtable menu of icecreams, and you want to implement the interface Iterator so you can browse all your icecreams
public class IteratorIceCream implements Iterator{
Hashtable icecreams;
public IteratorIceCream( Hashtable icecreams){
this.icecreams = icecreams;
}
public Object next(){
//implement
}
public boolean hasNext(){
//implement hasNext()
}
}
So you can create in class IceCreamMenu
public Iterator createIterator(){
}
Simple iterator coding is utilized to build the IteratorIceCream. There are inbuilt functions for iterator such as hasNext() and next(). We can get the value of hashtable using get(key) function where key is the key of the hashtable and the values over which the iterator iterates.
class IteratorIceCream implements Iterator{
Hashtable icecreams;
Iterator<Object> itr;
public IteratorIceCream( Hashtable icecreams){
this.icecreams = icecreams;
itr = icecreams.keySet().iterator(); // get iterator over set
entries
}
public Object next(){
return itr.next();
}
public boolean hasNext(){
return itr.hasNext();
}
}
We can create in class IceCreamMenu
public Iterator createIterator(){
return new IteratorIceCream (icecreamsHashtable); // where
icecreamsHashtable is hashtable of icecreams
}
Get Answers For Free
Most questions answered within 1 hours.