前面學習總結了List的使用及效率對比,今天總結學習一下鍵值映射關係Map,順便學習一下Android中使用Map須要注意哪些,以及谷歌官方針對Android對Map作了哪些優化。編程
Map 是一種把鍵對象和值對象映射的集合,它的每個元素都包含一對鍵對象和值對象。 Map沒有繼承於Collection接口 從Map集合中檢索元素時,只要給出鍵對象,就會返回對應的值對象。 數組
Map是一個接口,實例化Map能夠採用下面的方式:安全
Map的基本操做:數據結構
這裏以最經常使用的HashMap爲例併發
添加數據性能
Map<Integer, String> hashMap = new HashMap<>(); for (int i = 0; i < maxCount; i++) { hashMap.put(i, String.valueOf(i)); }
遍歷entrySet方式學習
long start = System.currentTimeMillis(); for (Map.Entry<Integer, String> entry : hashMap.entrySet()) { Integer key=entry.getKey(); String value=entry.getValue(); Log.i(TAG, "key: " + key +"value: "+value); } long end = System.currentTimeMillis(); Log.e(TAG, "for-each方式 cost time : " + (end - start));
entrySet迭代器遍歷方式優化
long start1 = System.currentTimeMillis(); Iterator<Map.Entry<Integer, String>> entries = hashMap.entrySet().iterator(); while (entries.hasNext()) { Map.Entry<Integer, String> entry = entries.next(); Integer key=entry.getKey(); String value=entry.getValue(); Log.i(TAG, "key: " + key +"value: "+value); } long end1 = System.currentTimeMillis(); Log.e(TAG, "entrySet iterator迭代器 cost time : " + (end1 - start1));
鍵找值遍歷spa
long end1 = System.currentTimeMillis(); Log.e(TAG, "iterator迭代器 cost time : " + (end1 - start1)); long start2 = System.currentTimeMillis(); for (Integer key : hashMap.keySet()) { String value = hashMap.get(key); Log.i(TAG, "key: " + key +"value: "+value); } long end2 = System.currentTimeMillis(); Log.e(TAG, "鍵找值遍歷 cost time : " + (end2 - start2));
keySet迭代器遍歷線程
long start3 = System.currentTimeMillis(); Iterator<Integer> iterator=hashMap.keySet().iterator(); while (iterator.hasNext()) { Integer key=iterator.next(); String value=hashMap.get(key); Log.i(TAG, "key: " + key +"value: "+value); } long end3 = System.currentTimeMillis(); Log.e(TAG, "keySet iterator迭代器 cost time : " + (end3 - start3));
上述四種狀況執行結果以下:
主要從新熟悉一下Map這種數據結構,以及更好的在之後的編程中選擇更合適的方式來進行key-value存儲。