Iterator Demo Two
package IteratorDemoTwo;
public interface Iterator {
boolean hasNext();
GroceryItem current();
void next();
}
package IteratorDemoTwo;
public class GroceryItem {
private int id;
private String name;
public GroceryItem(int id, String name) {
this.id = id;
this.name = name;
}
@Override
public String toString() {
return "Grocery Item{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
package IteratorDemoTwo;
import java.util.ArrayList;
import java.util.List;
public class GroceryCollection
{
private List<GroceryItem> products = new ArrayList<>();
public void add(GroceryItem product) {
products.add(product);
}
public Iterator createIterator() {
return new ListIterator(this);
}
private class ListIterator implements Iterator {
private GroceryCollection collection;
private int index;
public ListIterator(GroceryCollection collection) {
this.collection = collection;
}
@Override
public boolean hasNext() {
return (index < collection.products.size());
}
@Override
public GroceryItem current() {
return collection.products.get(index);
}
@Override
public void next() {
index++;
}
}
}