0

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();
        }
    }
}
3
  • 1
    Exactly what do you need to iterate over? Given some node, do you want to iterate over its direct descendants or all descendants? The former is trivial, the latter is a little complicated. Commented Oct 11, 2010 at 0:03
  • What should the iteration order be? And how does someone add nodes to your ArrayTree class anyway? Commented Oct 11, 2010 at 1:13
  • 1
    Regarding your previous question: If you find the answer helpful (which it seems you did, as you posted (and received answer to) 8 follow-up questions), you should upvote the answer instead of deleting the whole question and answers along with it. Commented Oct 11, 2010 at 6:30

2 Answers 2

2

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();
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

2 Comments

This isn't an answer is it? He'd still need to implement the iteration logic in a iterator() method. Simply marking the class as implements Iterable wouldn't help
It IS an answer. This is homework. He needs to try. When he does what I've suggested, he'll see something about methods that have to be implemented, perhaps the light will come on. Otherwise, he can ask a more specific question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.