Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Demo

Iterator Interface

Code Block
languagejava
package IteratorDemoOne;
public interface Iterator {
    boolean hasNext();
    String current();
    void next();
}

BrowseHistory

Code Block
languagejava
package IteratorDemoOne;

public class BrowseHistory {
    private String[] urls = new String[10];
    private int count;

    public void push(String url) {
        urls[count++] = url;
    }

    public String pop() {
        return urls[--count];
    }

    public Iterator createIterator() {
        return new ArrayIterator(this);
    }

    public class ArrayIterator implements Iterator {
        private BrowseHistory history;
        private int index;

        public ArrayIterator(BrowseHistory history) {
            this.history = history;
        }

        @Override
        public boolean hasNext() {
            return (index < history.count);
        }

        @Override
        public String current() {
            return history.urls[index];
        }

        @Override
        public void next() {
            index++;
        }
    }

}

Driver

Code Block
languagejava
package IteratorDemoOne;

public class IteratorDriver {
    public static void main(String[] args)
    {
        var myHistory = new BrowseHistory();
        myHistory.push("www.google.com");
        myHistory.push("www.alamo.edu");
        myHistory.push("www.amazon.com");

        Iterator myIterator =  myHistory.createIterator();
        while(myIterator.hasNext()){
            var url = myIterator.current();
            System.out.println(url);
            myIterator.next();
        }
    }
}

...