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

« Previous Version 2 Current »

Demo

Iterator Interface

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

BrowseHistory

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

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();
        }
    }
}

  • No labels