-5

May you explain the following statement about the code:

Collection<String> stringCollection = new HashSet<String>();
stringCollection.add(new String ("bye"));
stringCollection.add(new String ("hi"));
stringCollection.add(new String ("bye again"));
for( Iterator<String> iter=stringCollection.iterator();
    iter.hasNext();){
         String str=iter.next();
         if(str.equals("hi"))
             iter.remove();
}
for (String str: stringCollection){
        if(str.equals("hi"))
               stringCollection.remove("hi");
}
System.out.println(stringCollection.size());

If we change the order of both loops, then the code will run without errors and print 2: Wrong there is a runtime error, But why it seems correct?

avivlevi
  • 13
  • 4
  • 1
    There are 3 very different questions asked here. Can you focus on a single one? That said, refer to http://stackoverflow.com/questions/223918/iterating-through-a-collection-avoiding-concurrentmodificationexception-when-re for a) and http://stackoverflow.com/questions/14150628/string-constant-pool-java for b) and http://stackoverflow.com/questions/16079931/java-lists-remove-method-works-only-for-second-last-object-inside-for-each-loo for c) – Tunaki Jun 28 '16 at 08:42
  • Tunaki: one question: What does happen in this specific code, that the order matters and `equal`? – avivlevi Jun 28 '16 at 08:57

1 Answers1

0

The error is caused because you try to remove an item of a collection while on a iteration loop, therefore whenever the remove method is called in this piece of code will throw a Concurrent Modification Exception.

for (String str : stringCollection) {
    if (str.equals("hi"))
        stringCollection.remove("hi");
}

The reason why there is no error if you run the code as posted is because the first loop removes the item "hi" and therefore the second loop never calls the stringCollection.remove(...).

And as mentioned by @Tunaki this is already explained here

Community
  • 1
  • 1
Julian
  • 192
  • 1
  • 12