HashMap Put During Iteration
Putting into a HashMap while iterating throws ConcurrentModificationException, while ConcurrentHashMap iterates weakly consistent without failing.
Code
import java.util.HashMap;
import java.util.Map;
import java.util.ConcurrentModificationException;
import java.util.concurrent.ConcurrentHashMap;
public class MapPutDuringIteration {
public static void main(String[] args) {
// HashMap:遍历途中 put 属于结构性修改,下一次 next() 即抛 CME
Map<String, Integer> scores = new HashMap<>();
scores.put("a", 1);
scores.put("b", 2);
try {
for (String key : scores.keySet()) {
scores.put("c", 3);
}
} catch (ConcurrentModificationException e) {
System.out.println("HashMap failed: " + e.getClass().getSimpleName());
}
// ConcurrentHashMap:弱一致遍历,边写边遍历不抛异常
// 但不保证遍历能看到迭代开始后写入的键
Map<String, Integer> concurrent = new ConcurrentHashMap<>();
concurrent.put("a", 1);
concurrent.put("b", 2);
for (String key : concurrent.keySet()) {
concurrent.put("c", 3);
}
System.out.println("ConcurrentHashMap iterated without exception");
System.out.println("size after = " + concurrent.size());
}
}How it works
The working surface is the class MapPutDuringIteration and the function main — everything else is wiring.
Iteration happens inside for (String key : scores.keySet()) — everything outside it runs once.
Points of care
- The toolchain of the language is the sole prerequisite.
Applying it
The declaration that matters most: public static void main(String[] args)
Running the file prints labeled results such as HashMap failed:, ConcurrentHashMap iterated without exception, size after = — every step leaves its own tagged line.
Statements that matter
Map<String, Integer> concurrent = new ConcurrentHashMap<>();
Map<String, Integer> scores = new HashMap<>();
concurrent.put("a", 1);
Interactive Tools for This Topic
FAQ
- What does HashMap Put During Iteration print when run?
- Run it as a complete program — the output lines carry labels such as `HashMap failed:`, `ConcurrentHashMap iterated without exception`, `size after =`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.