java HashMap,TreeMap與LinkedHashMap的詳解
今天上午面試的時候 問到了Java,Map相關的事情,我記錯了HashMap和TreeMap相關的內容,回來趕緊嘗試了幾個demo理解下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
|
package Map; import java.util.*; public class HashMaps { public static void main(String[] args) { Map map = new HashMap(); map.put( "a" , "aaa" ); map.put( "b" , "bbb" ); map.put( "c" , "ccc" ); map.put( "d" , "ddd" ); Iterator iterator = map.keySet().iterator(); while (iterator.hasNext()) { Object key = iterator.next(); System.out.println( "map.get(key) is :" + map.get(key)); } Hashtable tab = new Hashtable(); tab.put( "a" , "aaa" ); tab.put( "b" , "bbb" ); tab.put( "c" , "ccc" ); tab.put( "d" , "ddd" ); Iterator iterator_1 = tab.keySet().iterator(); while (iterator_1.hasNext()) { Object key = iterator_1.next(); System.out.println( "tab.get(key) is :" + tab.get(key)); } TreeMap tmp = new TreeMap(); tmp.put( "a" , "aaa" ); tmp.put( "b" , "bbb" ); tmp.put( "c" , "ccc" ); tmp.put( "d" , "ddd" ); tmp.put( "a" , "aba" ); Iterator iterator_2 = tmp.keySet().iterator(); while (iterator_2.hasNext()) { Object key = iterator_2.next(); System.out.println( "tmp.get(key) is :" + tmp.get(key)); } LinkedHashMap<String ,Integer> linkedHashMap = new LinkedHashMap<String,Integer>(); linkedHashMap.put( "dasdsa" , 1 ); linkedHashMap.put( "gdsf" , 2 ); linkedHashMap.put( "texvdfd" , 3 ); linkedHashMap.put( "bdada" , 4 ); linkedHashMap.put( "gdsf" , 3 ); for (String temp : linkedHashMap.keySet()){ System.out.println(temp); } } } |
Map不同于 List, 底層使用 鍵值對的形式存儲數據 Map.Entry是內部的一個子條目,Map的不同實現 對鍵值對的索引方案不同
HashMap 本身是用hash函數對鍵值做索引 我們不能確定最后鍵值的順序
但是存在一個有趣的現象 就是在以Integer作為鍵值對的時候,當位數為1位時 鍵值是按照從小到大排的,位數上升到兩位的時候 就可能存在問題
TreeMap 內部存在著一個平衡樹來存儲著鍵值索引,TreeMap 把鍵值按照比較函數排序,我推測內部是可能存在著一個AVLtree
LinkedHashMap 這個存在著一個特性是,鍵值對是按照插入順序排序的,如果存在著重復插入,以首次插入的順序來記,網上的一種說法是該結構內部存在著2重hash
一個解決順序問題,一個解決存儲問題,正確性待確認
HashMap和TreeMap 是最常用的兩種Map結構, 一般來說HashMap的效率比較高,也最為常見,如果我們需要鍵值有序的話,我們才會用到TreeMap
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
原文鏈接:http://blog.csdn.net/u010953266/article/details/45933883