Skip to end of metadata
Go to start of metadata
You are viewing an old version of this page. View the current version.
Compare with Current
View Page History
Version 1
Current »
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++;
}
}
}
package IteratorDemoTwo;
public class IteratorDriveTwo {
public static void main(String[] args) {
var collection = new GroceryCollection();
collection.add(new GroceryItem(1, "Beans"));
collection.add(new GroceryItem(2, "Corn"));
collection.add(new GroceryItem(3, "Bread"));
var iterator = collection.createIterator();
while (iterator.hasNext()) {
System.out.println(iterator.current());
iterator.next();
}
}
}