1 package com.journaldev.util; 2 3 import java.util.HashMap; 4 import java.util.Iterator; 5 import java.util.Map; 6 import java.util.concurrent.ConcurrentHashMap; 7 8 public class ConcurrentHashMapExample { 9 10 public static void main(String[] args) { 11 12 //ConcurrentHashMap 13 Map<String,String> myMap = new ConcurrentHashMap<String,String>(); 14 myMap.put("1", "1"); 15 myMap.put("2", "1"); 16 myMap.put("3", "1"); 17 myMap.put("4", "1"); 18 myMap.put("5", "1"); 19 myMap.put("6", "1"); 20 System.out.println("ConcurrentHashMap before iterator: "+myMap); 21 Iterator<String> it = myMap.keySet().iterator(); 22 23 while(it.hasNext()){ 24 String key = it.next(); 25 if(key.equals("3")) myMap.put(key+"new", "new3"); 26 } 27 System.out.println("ConcurrentHashMap after iterator: "+myMap); 28 29 //HashMap 30 myMap = new HashMap<String,String>(); 31 myMap.put("1", "1"); 32 myMap.put("2", "1"); 33 myMap.put("3", "1"); 34 myMap.put("4", "1"); 35 myMap.put("5", "1"); 36 myMap.put("6", "1"); 37 System.out.println("HashMap before iterator: "+myMap); 38 Iterator<String> it1 = myMap.keySet().iterator(); 39 40 while(it1.hasNext()){ 41 String key = it1.next(); 42 if(key.equals("3")) myMap.put(key+"new", "new3"); 43 } 44 System.out.println("HashMap after iterator: "+myMap); 45 } 46 47 }
package com.journaldev.util; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public class ConcurrentHashMapExample { public static void main(String[] args) { //ConcurrentHashMap Map<String,String> myMap = new ConcurrentHashMap<String,String>(); myMap.put("1", "1"); myMap.put("2", "1"); myMap.put("3", "1"); myMap.put("4", "1"); myMap.put("5", "1"); myMap.put("6", "1"); System.out.println("ConcurrentHashMap before iterator: "+myMap); Iterator<String> it = myMap.keySet().iterator(); while(it.hasNext()){ String key = it.next(); if(key.equals("3")) myMap.put(key+"new", "new3"); } System.out.println("ConcurrentHashMap after iterator: "+myMap); //HashMap myMap = new HashMap<String,String>(); myMap.put("1", "1"); myMap.put("2", "1"); myMap.put("3", "1"); myMap.put("4", "1"); myMap.put("5", "1"); myMap.put("6", "1"); System.out.println("HashMap before iterator: "+myMap); Iterator<String> it1 = myMap.keySet().iterator(); while(it1.hasNext()){ String key = it1.next(); if(key.equals("3")) myMap.put(key+"new", "new3"); } System.out.println("HashMap after iterator: "+myMap); } }
时间: 2024-11-05 13:44:42