java 集合类遍历

 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进行遍历。

 

QQ截图未命名

 

经过测试前者确实效率高,遍历代码如下:

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循环等要慢得多,尤其在分布式缓存情况下

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章