Question

I'm having an issue with the same code running on two different versions of the JDK. The code basically has nested iterators on the same HashMap. The following is pseudocode. I've inherited this code...

Iterator entries = source.entrySet().iterator();
while(entries.hasNext()) {
    Map.Entry entry = entries.next();

    Iterator otherEntries = source.entrySet().iterator();
    while(otherEntries.hasNext()) {
        Map.Entry otherEntry = otherEntries.next();
        List elements = otherEntry.getValue();

        for(element : elements) {
            ...
        }

        for(someOtherElement : someOtherElement) { 
            if(...) {
                elements.add(someOtherElement);
            }
        }
    }
}

Apologies for the mess of this code but as I mentioned I inherited this. This code runs fine for us in JDK 1.7. In JDK 1.6 (an IBM RSA JDK), the call to "elements.add(...)" also adds the elements to the original "source" HashMaps elements. The "elements" List comes from otherEntry.getValue(). Adding or updating elements seems to cause the source to be updated as it is passed by reference. However, in JDK 1.7 (just a standard one), we don't see the same behaviour. Here calls to "elements.add" do not update or modify the "source" HashMap.

So I'm trying to understand whats going on here and is this something that was changed between JDK's??

Thanks

Was it helpful?

Solution

There is no change in the behavior of the way instance are passed. But the question whether you see modified list elements depends on the iteration order: you will see modified lists only if you modify lists contained in entries that not have been seen already by the outer Iterator. Since the iteration order might change between different HashMap implementations it might really happen that you see modified lists in one JDK but not another.

The bottom line is that you should not use such nested Iterators. When modifying in one loop and looking into it in another loop after the first loop has been finished you will see the modified lists, reliably.

OTHER TIPS

The only change I can see from source code is

Three new methods have been added Collections class namely

Collections.emptyIterator
Collections.emptyEnumeration
Collections.emptyListIterator
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top