Adam
Adam

Reputation: 10016

Changing the object on which an iterator was created

Consider the function below:

private static void printTrie(Node root){
        Iterator it = root.children.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry pair = (Map.Entry)it.next();
            System.out.println((Character)pair.getKey());
            root = (Node)pair.getValue();
            printTrie(root);
            it.remove(); // avoids a ConcurrentModificationException
        }
    }

Here's the definition of Node:

static class Node {
        private HashMap<Character, Node> children;
        private boolean isCompleteContact;

        public Node(){
            children = new HashMap<Character, Node>();
            isCompleteContact = false;
        }
    }

My question is this: in the function I create an Iterator called it based on root. However, halfway through iterating over all the elements exposed by it, I reassign root to another node. Does this change the behaviour of the it? I.e., does it still refer to the original root or the new value we assign to root halfway through the while loop?

Upvotes: 1

Views: 644

Answers (2)

Chetan Kinger
Chetan Kinger

Reputation: 15212

Since Java is always pass-by-value, the reassignment of the root reference will not reassign the root object/instance but just the root reference.

The statement root = (Node)pair.getValue(); only reassings the local reference root to a new object. You will continue to iterate over the original root object since the iterator was created on the original root object which can't be reassigned due to pass-by-value semantics.

Also note that if you add a new value to the children HashMap while iterating over it, it will result in a ConcurrentModficationException. The only thing you can do safetly using the same iterator is remove the current element being iterated by calling remove on the Iterator

Upvotes: 1

Horia Coman
Horia Coman

Reputation: 8781

It refers to the original object root was referring to. This is because the iterator is derived from the value of the variable root, rather than it, itself, as a reference to that value.

Upvotes: 2

Related Questions