import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
public class TestMap {
/* 在遍历Map过程中,不能用map.put(key,value),map.remove(key)来修改和删除元素, 会引发并发修改异常*/
public static void main(String[] args) {
HashMap<String, String> testMap = new HashMap<String,String>();
testMap.put(“1″,”test1”);
testMap.put(“2″,”test2”);
testMap.put(“2″,”test2”);
testMap.put(“2″,”test2”);
testMap.put(“3″,”test3”);
testMap.put(“4″,”test4”);
testMap.put(“4″,”test4”);
testMap.put(“4″,”test4”);
Set mapSet = testMap.entrySet();
Iterator iterator = mapSet.iterator();
while(iterator.hasNext())
{
Map.Entry mapEntry = (Map.Entry) iterator.next();
String key = mapEntry.getKey().toString();
String value = mapEntry.getValue().toString();
System.out.printf(“key: %s value:%s\r\n”, key, value);
}
System.out.printf(“***************deleting************\r\n”);
Iterator<Map.Entry<String, String>> it = testMap.entrySet().iterator();
while(it.hasNext())
{
Map.Entry<String,String> entry = it.next();
String key = entry.getKey();
int k = Integer.parseInt(key);
if(k%2==1)
{
System.out.printf(“delete key:%s value:%s\r\n”, key, entry.getValue());
it.remove();
}
}
System.out.printf(“*****************result***********\r\n”);
iterator = mapSet.iterator();
while(iterator.hasNext())
{
Map.Entry mapEntry = (Map.Entry)iterator.next();
String key = mapEntry.getKey().toString();
String value = mapEntry.getValue().toString();
System.out.printf(“key:%s value:%s\r\n”, key,value);
}
}
}
出自http://www.dedecms.com/knowledge/program/jsp-java/2012/0810/4490.html