本文共 1636 字,大约阅读时间需要 5 分钟。
import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.TreeMap; public class TreeMapTest { public static void main(String[] args) { Mapmap=new TreeMap (); map.put("tom", new Person(16)); map.put("jim", new Person(17)); map.put("zose", new Person(18)); for(Map.Entry entry:map.entrySet()){ if(entry.getKey().equals("tom")){ map.remove("tom"); System.out.println("find tom"); } else{ System.out.println(entry.getValue().getAge()); } } System.out.println(map.size()); } } class Person{ int age; public Person(int age){ this.age=age; } public int getAge(){ return age; } }
collection(由此类所有的“collection 视图方法”返回)的 iterator 方法返回的迭代器都是快速失败 的:在迭代器创建之后,如果从结构上对映射进行修改,除非通过迭代器自身的 remove 方法,否则在其他任何时间以任何方式进行修改都将导致迭代器抛出 ConcurrentModificationException。因此调用map.remove(“tom”),进入下次循环后,直接抛出ConcurrentModificationException异常,正确答案是:
17find tomConcurrentModificationException
同时,如果要在TreeMap中删除元素,应该采用迭代器的方式
Setset=map.keySet(); Iterator it=set.iterator(); while(it.hasNext()){ String key=it.next(); if(key.equals("tom")){ it.remove(); System.out.println("find tom"); } else { System.out.println(map.get(key).getAge()); } }
转载地址:http://nnzsl.baihongyu.com/