In the project there is a demand, need a Set type collection to meet the conditions to remove the object, then take it for granted thought to directly call Set the remove (Object o) method to delete the specified object can be.
However, when running the program, they found a mistake:
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.HashMap $ HashIterator.nextEntry (Unknown Source)
at java.util.HashMap $ KeyIterator.next (Unknown Source)
at test.Test.main (Test.java: 23)
List can be seen from the API, the realization of such Collection is not synchronized, if you appear in multi-threaded applications simultaneously access and modify the operation occurs when the external operations require synchronization; Diaoyong Iterator Iterator object operations get multi-threading Set modification time is automatically invalidated and thrown java.util.ConcurrentModificationException. This implementation mechanism is fail-fast, on the external changes and can not provide any guarantee.
Iterator is working in a separate thread, Iterator is created when the establishment of a memory index table (single list), the index table points to the original object, when the number of objects to change the original time, the index table of content without same pace, so when the index pointer moves down, it will not find the object to be iterative, so an error occurs. List, Set, etc. are dynamic, variable number of objects in the data structure, but the Iterator is immutable one-way only in order to read, can not reverse operation of the data structure, when the Iterator pointing to the original data is changed, Iterator own the lost.
How can it meet demand, need to define a List, to save the need to remove the object.