Funny error with Java’s extended for-loop
Java 5 introduced the enhanced for-loop – or for-each loop – which simplifies iterating over many types of collections. Have a look at this simple piece of code and tell me what’s wrong: package de.danielschneller.blog.iterator; import java.util.HashSet; import java.util.Set; public class Demo { public static void main(String[] args) { Set set = new HashSet (); set.add("Value 1"); set.add("Value 2"); set.add("Value 3"); set.add("Value 4"); set.add("Value 5"); synchronized (set) { for (String tEntry : set) { if (tEntry.endsWith("3")) { System.out.println("3 has to go"); set.remove(tEntry); } else { System.out.println(tEntry + " may stay"); } } } } } When I wrote this I naively expected something like this to be written out(the order of the iteration is undefined for a HashSet, but bear with me: Value 5 may stay Value 2 may stay 3 has to go