0

I have implemented an AVL tree and I wanted to write an Iterator, that searches in pre order. I have this peace of code and I get always a NullPointer in "stack.push(current)" and dont know why

@Override
public Iterator<E> iterator() {

    return new Iterator<E>(){
        Node current;
        int counter;
        Stack<Node> stack;

        public void iterator() {
            counter++;
            stack = new Stack<Node>();
            current = root;
            stack.empty();
        }
        @Override
        public boolean hasNext() {
            if(counter == count(root)) return false;
            else return true;
        }

        @Override
        public E next() {
            stack.push(current);
            counter++;
            if(current.left.value != null) return current.left.value;
            else return current.right.value;
        }

    };
}

Thanks in beforehand :)

Maxim
  • 231
  • 3
  • 16
  • 1
    Possible duplicate of [What is a Null Pointer Exception, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it) – Idos Jan 07 '16 at 16:00
  • What is `current = root;`? Where has root been instantiated? – jgabb Jan 07 '16 at 16:02
  • This is just a segment of my whole code. At the beginning of my code i have instantiated the root – Maxim Jan 07 '16 at 16:06

1 Answers1

0

Your root object was never declared or instantiated. You are setting current = root; but in the current context, root is nothing.

public void iterator() {
        counter++;
        stack = new Stack<Node>();
        current = root;
        stack.empty();
    }
jgabb
  • 542
  • 1
  • 4
  • 20
  • Even if I instantiate the root within my iterator and give him the value of the root or null, I also get an NullPointer. I can write him within the method, but which value I should use then? – Maxim Jan 07 '16 at 16:15