-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?

2

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.