- Package net.nie.test;
- Import Java.util.HashMap;
- Import Java.util.Iterator;
- Import Java.util.Map;
- Public class Hashmaptest {
- private static Map<integer, string> map=new hashmap<integer,string> ();
- /** 1.HashMap class mappings are not guaranteed in order; some mappings can be explicitly guaranteed in their order: TreeMap class
- * 2. Map.put (Key,newval), Map.Remove (key) cannot be used to modify and delete elements during traversal of the map.
- * Causes concurrent modification exceptions, which can be passed through the iterator's remove ():
- * Removes the current iteration element from the collection that the iterator points to
- * To achieve the purpose of deleting elements in the access.
- * */
- public static void Main (string[] args) {
- Map.put (1,"one");
- Map.put (2,"a");
- Map.put (3,"three");
- Map.put (4,"four");
- Map.put (5,"Five");
- Map.put (6,"Six");
- Map.put (7,"seven");
- Map.put (8,"eight");
- Map.put (5,"Five");
- Map.put (9,"Nine");
- Map.put (Ten);
- Iterator<map.entry<integer, string>> it = Map.entryset (). Iterator ();
- While (It.hasnext ()) {
- Map.entry<integer, string> entry=it.next ();
- int Key=entry.getkey ();
- if (key%2==1) {
- System.out.println ("Delete this:" +key+"=" +key);
- //map.put (Key, "odd"); Concurrentmodificationexception
- //map.remove (key); Concurrentmodificationexception
- It.remove (); //ok
- }
- }
- //traverse the current map; This new for loop cannot modify the map content because it does not pass through the iterator.
- System.out.println ("-------\n\t elements of the final map traversal:");
- for (Map.entry<integer, string> entry:map.entrySet ()) {
- int K=entry.getkey ();
- String V=entry.getvalue ();
- System.out.println (k +"=" +v);
- }
- }
- }
Basic type, there is no exception.
List in
(1). There is no exception when using the index traversal, but the subsequent data may be problematic;
(2). List with enhanced for loop over duration: Exception is reported java.util.ConcurrentModificationException
(except for immediate break after deletion)
(3). There is no problem with iterators iterator.remove () when iterating.
Delete element when Java traverses map