日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

android 变量Map集合

發布時間:2024/4/15 编程问答 25 豆豆
生活随笔 收集整理的這篇文章主要介紹了 android 变量Map集合 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.


今天,簡單講講android如何遍歷Map集合。


這個其實很簡單,但是之前忘記了,查找資料才記起的,所以記錄一下。


以下是map遍歷的四種方式:

// 一、推薦只用value的時候用,都懂的。。。 // Map.values()遍歷所有的value,不遍歷key for (String v : map.values()) { System.out.println("value= " + v); }


// 二、取二次值,先取key再取value,建議只需要用key的時候使用,節省時間、空間 // keySet遍歷key和value for (String key : map.keySet()) { System.out.println("key= "+ key + " and value= " + map.get(key)); }


// 三、取一次值,一次把key和value全部取出 // entrySet使用iterator遍歷key和value Iterator<Map.Entry<String, String>> it = map.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, String> entry = it.next(); System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue()); }


// 四、推薦,尤其是容量大時,TreeMap尤其推薦 // entrySet遍歷key和value for (Map.Entry<String, String> entry : map.entrySet()) { System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue()); }


五.不使用泛型:

Map map = new HashMap();Iterator entries = map.entrySet().iterator();while (entries.hasNext()) {Map.Entry entry = (Map.Entry) entries.next();Integer key = (Integer)entry.getKey();Integer value = (Integer)entry.getValue();System.out.println("Key = " + key + ", Value = " + value);}



通過鍵找值遍歷(效率低)

Map<Integer, Integer> map = new HashMap<Integer, Integer>();for (Integer key : map.keySet()) {Integer value = map.get(key);System.out.println("Key = " + key + ", Value = " + value);}


作為方法一的替代,這個代碼看上去更加干凈;但實際上它相當慢且無效率。因為從鍵取值是耗時的操作(與方法一相比,在不同的Map實現中該方法慢了20%~200%)。如果你安裝了FindBugs,它會做出檢查并警告你關于哪些是低效率的遍歷。所以盡量避免使用。


3. 結論
3.1 如果你使用HashMap
同時遍歷key和value時,keySet與entrySet方法的性能差異取決于key的具體情況,如復雜度(復雜對象)、離散度、沖突率等。換言之,取決于HashMap查找value的開銷。entrySet一次性取出所有key和value的操作是有性能開銷的,當這個損失小于HashMap查找value的開銷時,entrySet的性能優勢就會體現出來。例如上述對比測試中,當key是最簡單的數值字符串時,keySet可能反而會更高效,耗時比entrySet少10%。總體來說還是推薦使用entrySet。因為當key很簡單時,其性能或許會略低于keySet,但卻是可控的;而隨著key的復雜化,entrySet的優勢將會明顯體現出來。當然,我們可以根據實際情況進行選擇
只遍歷key時,keySet方法更為合適,因為entrySet將無用的value也給取出來了,浪費了性能和空間。在上述測試結果中,keySet比entrySet方法耗時少23%。
只遍歷value時,使用vlaues方法是最佳選擇,entrySet會略好于keySet方法。


這里是從網上找到的資料,有興趣的可以自己去查找別人的資料。


android 變量Map集合就講完了。


就這么簡單。



總結

以上是生活随笔為你收集整理的android 变量Map集合的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。