ArrayList list2 = new ArrayList();
list2.add("java");
list2.add("php");
list2.add(".net");
Iterator it=list2.iterator();
while(it.hasNext()){
it.next();
it.remove();
} //能完成删除,list最终为空,因此it指向的是与list2相同的空间
// while(it. hasNext()){
// Object obj=it.next();
// list2.remove(obj);
// } //将会报Exception in thread "main" java.util.ConcurrentModificationException异常
遍历map的方式,一般来说
无意中看见代码扫描出的一些performance警告,大意是建议使用entrySet 代替KeySet对Map进行遍历。
经过测试前者确实效率高,遍历代码如下:
public class MyMap {
public static void main(String[] args) {
Map<String,Integer> map=new HashMap<String,Integer>();
map.put("jessica",100);
map.put("tom",200);
map.put("den",300);
Set<Map.Entry<String, Integer>> set =map.entrySet();
for (Map.Entry<String, Integer> per : set) {
System.out.println(per.getKey() + ":" + per.getValue());
}
}
}
除此之外,实践发现:集合类遍历,转成iterator方式比较for循环等要慢得多,尤其在分布式缓存情况下
本文探讨了Java中ArrayList的遍历与删除操作的区别,特别是Iterator与直接使用List对象删除元素之间的差异,并通过实例说明了遍历Map时使用entrySet而非keySet所带来的性能优势。

1037

被折叠的 条评论
为什么被折叠?



