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循環等要慢得多,尤其在分佈式緩存情況下

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