Code Block | ||
---|---|---|
| ||
package IteratorDemoTwo; public interface Iterator { boolean hasNext(); GroceryItem current(); void next(); } |
Code Block | ||
---|---|---|
| ||
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 + '\'' + '}'; } } |
Code Block | ||
---|---|---|
| ||
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++; } } } |
Code Block | ||
---|---|---|
| ||
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(); } } } |