- Map的正确使用
for(Map.Entry<String, String> entry: params.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); }
Iterator<Entry<UserEntity, Long>> iter = countTaskOfUserMap.entrySet().iterator(); while(iter.hasNext()){ Map.Entry entry = (Map.Entry)iter.next(); UserEntity key = (UserEntity)entry.getKey(); long value = (Long)entry.getValue(); }
注意 ,当map遍历判断筛选删除时,不能用map.remove直接删除,而应使用迭代删除,不要会报错invalid_loop: Attempting to obtain another element from "map.entrySet()" after it‘s been modified,代码如下
1 mport java.util.HashMap; 2 import java.util.Iterator; 3 import java.util.Map; 4 5 public class HashMapTest { 6 private static Map<Integer, String> map=new HashMap<Integer,String>(); 7 8 /** 1.HashMap 类映射不保证顺序;某些映射可明确保证其顺序: TreeMap 类 9 * 2.在遍历Map过程中,不能用map.put(key,newVal),map.remove(key)来修改和删除元素, 10 * 会引发 并发修改异常,可以通过迭代器的remove(): 11 * 从迭代器指向的 collection 中移除当前迭代元素 12 * 来达到删除访问中的元素的目的。 13 * */ 14 public static void main(String[] args) { 15 map.put(1,"one"); 16 map.put(2,"two"); 17 map.put(3,"three"); 18 map.put(4,"four"); 19 map.put(5,"five"); 20 map.put(6,"six"); 21 map.put(7,"seven"); 22 map.put(8,"eight"); 23 map.put(5,"five"); 24 map.put(9,"nine"); 25 map.put(10,"ten"); 26 Iterator<Map.Entry<Integer, String>> it = map.entrySet().iterator(); 27 while(it.hasNext()){ 28 Map.Entry<Integer, String> entry=it.next(); 29 int key=entry.getKey(); 30 if(key%2==1){ 31 System.out.println("delete this: "+key+" = "+key); 32 //map.put(key, "奇数"); //ConcurrentModificationException 33 //map.remove(key); //ConcurrentModificationException 34 it.remove(); //OK 35 } 36 } 37 //遍历当前的map;这种新的for循环无法修改map内容,因为不通过迭代器。 38 System.out.println("-------\n\t最终的map的元素遍历:"); 39 for(Map.Entry<Integer, String> entry:map.entrySet()){ 40 int k=entry.getKey(); 41 String v=entry.getValue(); 42 System.out.println(k+" = "+v); 43 } 44 } 45 }