Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Code Block
languagejava
package IteratorDemoTwo;

public interface Iterator {
    boolean hasNext();
    GroceryItem current();
    void next();
}

Code Block
languagejava
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
languagejava
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
languagejava
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();
        }
    }
}
Image RemovedImage Added