user258875
user258875

Reputation:

Java Array Tree Iterator

I am trying to write a class that implements a tree using an array and I need some help to write an Iterator method that which returns an iterator of the elements stored in the tree.

Solution:

public Iterator<E> iterator() {
    return new Iterator<E>() {
        private int index = 0;

        public boolean hasNext() {
            return index < ArrayTree.this.size();
        }

        public E next() {
           if (!hasNext()) {
               return new NoSuchElementException();
           }
           return ArrayTree.this.tree[index++];
        }

        public void remove() {
            return new OperationNotSupported();
        }
    }
}

Upvotes: 0

Views: 3809

Answers (2)

Steve Emmerson
Steve Emmerson

Reputation: 7832

Without examining your implementation very closely, a very simple implementation might be

public Iterator<E> iterator() {
    return new Iterator<E>() {
        private int index = 0;

        public boolean hasNext() {
            return index < ArrayTree.this.size();
        }

        public E next() {
           if (!hasNext()) {
               return new NoSuchElementException();
           }
           return ArrayTree.this.tree[index++];
        }

        public void remove() {
            return new OperationNotSupported();
        }
    }
}

Upvotes: 2

Tony Ennis
Tony Ennis

Reputation: 12299

There are a couple of ways to go, but if your ArrayTree class implements Iterable and Iterator interfaces you'll be on your way.

Upvotes: 0

Related Questions