import
java.util.HashMap;
import
java.util.Iterator;
import
java.util.LinkedHashMap;
import
java.util.Map;
public
class
TestLinkedHashMap {
public
static
void
main(String args[])
{
System.out.println(
"*************************LinkedHashMap*************"
);
Map<Integer,String> map =
new
LinkedHashMap<Integer,String>();
map.put(
6
,
"apple"
);
map.put(
3
,
"banana"
);
map.put(
2
,
"pear"
);
for
(Iterator it = map.keySet().iterator();it.hasNext();)
{
Object key = it.next();
System.out.println( key+
"="
+ map.get(key));
}
System.out.println(
"*************************HashMap*************"
);
Map<Integer,String> map1 =
new
HashMap<Integer,String>();
map1.put(
6
,
"apple"
);
map1.put(
3
,
"banana"
);
map1.put(
2
,
"pear"
);
for
(Iterator it = map1.keySet().iterator();it.hasNext();)
{
Object key = it.next();
System.out.println( key+
"="
+ map1.get(key));
}
}
}
運行結果如下:
*************************LinkedHashMap*************
6=apple
3=banana
2=pear
*************************HashMap**************************
2=pear
6=apple
3=banana
分析:LinkedHashmap 的特點是put進去的對象位置未發生變化,而HashMap會發生變化.
再普及下:
java為數據結構中的映射定義了一個接口java.util.Map;它有四個實現類,分別是HashMap Hashtable LinkedHashMap 和TreeMap.
Map主要用於存儲健值對,根據鍵得到值,因此不允許鍵重復(重復了覆蓋了),但允許值重復。
Hashmap
是一個最常用的Map,它根據鍵的HashCode值存儲數據,根據鍵可以直接獲取它的值,具有很快的訪問速度,遍歷時,取得數據的順序是完全隨機的。 HashMap最多只允許一條記錄的鍵為Null(如果建是null存在數組的第一個位置);允許多條記錄的值為 Null;HashMap不支持線程的同步,即任一時刻可以有多個線程同時寫HashMap;可能會導致數據的不一致。如果需要同步,可以用 Collections的synchronizedMap方法使HashMap具有同步的能力,或者使用ConcurrentHashMap。
默認初始化的時候是16個數組的大小,而且增長是成倍的增長。
/** * Constructs an empty <tt>HashMap</tt> with the default initial capacity * (16) and the default load factor (0.75). */ public HashMap() { this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR); }
void addEntry(int hash, K key, V value, int bucketIndex) { if ((size >= threshold) && (null != table[bucketIndex])) { resize(2 * table.length); hash = (null != key) ? hash(key) : 0; bucketIndex = indexFor(hash, table.length); } createEntry(hash, key, value, bucketIndex); }
Hashtable
與 HashMap類似,它繼承自Dictionary類,不同的是:它不允許記錄的鍵或者值為空;它支持線程的同步,即任一時刻只有一個線程能寫Hashtable,因此也導致了 Hashtable在寫入時會比較慢。
默認初始化的時候是11個數組的大小,而且增長是old*2+1
public Hashtable() { this(11, 0.75f); }
LinkedHashMap
是HashMap的一個子類,保存了記錄的插入順序,在用Iterator遍歷LinkedHashMap時,先得到的記錄肯定是先插入的.也可以在構造 時用帶參數,按照應用次數排序。在遍歷的時候會比HashMap慢,不過有種情況例外,當HashMap容量很大,實際數據較少時,遍歷起來可能會比 LinkedHashMap慢,因為LinkedHashMap的遍歷速度只和實際數據有關,和容量無關,而HashMap的遍歷速度和他的容量有關。
TreeMap
實現SortMap接口,能夠把它保存的記錄根據鍵排序,默認是按鍵值的升序排序,也可以指定排序的比較器,當用Iterator 遍歷TreeMap時,得到的記錄是排過序的。
一 般情況下,我們用的最多的是HashMap,在Map 中插入、刪除和定位元素,HashMap 是最好的選擇。但如果您要按自然順序或自定義順序遍歷鍵,那么TreeMap會更好。如果需要輸出的順序和輸入的相同,那么用LinkedHashMap 可以實現,它還可以按讀取順序來排列.