HashMap,LinkedHashMap,TreeMap都屬于Map;Map 主要用于存儲鍵(key)值(value)對,根據鍵得到值,因此鍵不允許鍵重復,但允許值重復。
不同點:
1.HashMap里面存入的鍵值對在取出的時候是隨機的,也是我們最常用的一個Map.它根據鍵的HashCode值存儲數據,根據鍵可以直接獲取它的值,具有很快的訪問速度。在Map 中插入、刪除和定位元素,HashMap 是最好的選擇。
2.TreeMap取出來的是排序后的鍵值對。但如果您要按自然順序或自定義順序遍歷鍵,那么TreeMap會更好。
3. LinkedHashMap 是HashMap的一個子類,如果需要輸出的順序和輸入的相同,那么用LinkedHashMap可以實現.
代碼實例:
package com.lrm.study.testcase;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TreeMap;
public class MapAppTest {
/**
* @Create on Nov 9, 2009 by lrm
*/
public static void main(String[] args) {
?? // TODO Auto-generated method stub
?? MapAppTest.noOrder();
?? MapAppTest.hasOrder();
?? MapAppTest.likedHashMap();
}
public static void noOrder() {
?? System.out.println("------無序(隨機輸出------");
?? Map map = new HashMap();
?? map.put("1", "Level 1");
?? map.put("2", "Level 2");
?? map.put("3", "Level 3");
?? map.put("4", "Level 4");
?? map.put("F", "Level F");
?? map.put("Q", "Level Q");
?? Iterator it = map.entrySet().iterator();
?? while (it.hasNext()) {
??? Map.Entry e = (Map.Entry) it.next();
??? System.out.println("Key: " + e.getKey() + ";?? Value: "
????? + e.getValue());
?? }
}
// 有序(默認排序,不能指定)
public static void hasOrder() {
?? System.out.println("------有序(但是按默認順充,不能指定)------");
?? Map map = new TreeMap();
?? map.put("F", "Level F");
?? map.put("7", "Level 1");
?? map.put("8", "Level 2");
?? map.put("4", "Level 3");
?? map.put("4", "Level 4");
?? map.put("Q", "Level Q");
?? map.put("E", "Level E");
?? Iterator it = map.entrySet().iterator();
?? while (it.hasNext()) {
??? Map.Entry e = (Map.Entry) it.next();
??? System.out.println("Key: " + e.getKey() + ";?? Value: "
????? + e.getValue());
?? }
}
public static void likedHashMap() {
?? System.out.println("------有序(根據輸入的順序輸出)------");
?? Map map = new LinkedHashMap();
?? map.put("F", "Level F");
?? map.put("7", "Level 1");
?? map.put("8", "Level 2");
?? map.put("4", "Level 3");
?? map.put("4", "Level 4");
?? map.put("Q", "Level Q");
?? map.put("E", "Level E");
?? Iterator it = map.entrySet().iterator();
?? while (it.hasNext()) {
??? Map.Entry e = (Map.Entry) it.next();
??? System.out.println("Key: " + e.getKey() + ";?? Value: "
????? + e.getValue());
?? }
}
}
輸出結果:
------無序(隨機輸出------
Key: 3;?? Value: Level 3
Key: F;?? Value: Level F
Key: 2;?? Value: Level 2
Key: 4;?? Value: Level 4
Key: Q;?? Value: Level Q
Key: 1;?? Value: Level 1
------有序(但是按默認順充,不能指定)------
Key: 4;?? Value: Level 4
Key: 7;?? Value: Level 1
Key: 8;?? Value: Level 2
Key: E;?? Value: Level E
Key: F;?? Value: Level F
Key: Q;?? Value: Level Q
------有序(根據輸入的順序輸出)------
Key: F;?? Value: Level F
Key: 7;?? Value: Level 1
Key: 8;?? Value: Level 2
Key: 4;?? Value: Level 4
Key: Q;?? Value: Level Q
Key: E;?? Value: Level E