Hashtable:同步,慢。數據量小
HashMap:不支持同步,快,數據量大
Properties:同步,文件形式,數據量小,不常用
LInkedHashMap:基於雙向鏈表的維持插入順序的HashMap
TreeMap:基於紅黑樹的Map,可以根據key的自然排需或者compareTo方法進行排序輸出。
常見方法:
Hashtable也是無序的。
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
public class HashtableTest {
public static void main(String[] args) {
Hashtable<Integer,String> ht =new Hashtable<Integer,String>();
//ht.put(1, null); 編譯不報錯 運行報錯
//ht.put(null,1); 編譯報錯
ht.put(1000, "aaa");
ht.put(2, "bbb");
ht.put(30000, "ccc");
System.out.println(ht.contains("aaa"));
System.out.println(ht.containsValue("aaa"));
System.out.println(ht.containsKey(30000));
System.out.println(ht.get(30000));
ht.put(30000, "ddd"); //更新覆蓋ccc
System.out.println(ht.get(30000));
//ht.remove(2);
System.out.println("size: " + ht.size());
//ht.clear();
//System.out.println("size: " + ht.size());
/*Hashtable<Integer,String> ht2 =new Hashtable<Integer,String>();
for(int i=0;i<100000;i++)
{
ht2.put(i, "aaa");
}*/
traverseByEntry(ht);
/*traverseByKeySet(ht2);
traverseByKeyEnumeration(ht2); */
}
public static void traverseByEntry(Hashtable<Integer,String> ht)
{
long startTime = System.nanoTime();
System.out.println("============Entry迭代器遍歷==============");
Integer key;
String value;
Iterator<Entry<Integer, String>> iter = ht.entrySet().iterator();
while(iter.hasNext()) {
Map.Entry<Integer, String> entry = iter.next();
// 獲取key
key = entry.getKey();
// 獲取value
value = entry.getValue();
System.out.println("Key:" + key + ", Value:" + value);
}
long endTime = System.nanoTime();
long duration = endTime - startTime;
System.out.println(duration + "納秒");
}
public static void traverseByKeySet(Hashtable<Integer,String> ht)
{
long startTime = System.nanoTime();
System.out.println("============KeySet迭代器遍歷==============");
Integer key;
String value;
Iterator<Integer> iter = ht.keySet().iterator();
while(iter.hasNext()) {
key = iter.next();
// 獲取value
value = ht.get(key);
//System.out.println("Key:" + key + ", Value:" + value);
}
long endTime = System.nanoTime();
long duration = endTime - startTime;
System.out.println(duration + "納秒");
}
public static void traverseByKeyEnumeration(Hashtable<Integer,String> ht)
{
long startTime = System.nanoTime();
System.out.println("============KeyEnumeration迭代器遍歷==============");
Integer key;
String value;
Enumeration<Integer> keys = ht.keys();
while(keys.hasMoreElements()) {
key = keys.nextElement();
// 獲取value
value = ht.get(key);
//System.out.println("Key:" + key + ", Value:" + value);
}
long endTime = System.nanoTime();
long duration = endTime - startTime;
System.out.println(duration + "納秒");
}
}
輸出:
true
true
true
ccc
ddd
size: 3
============Entry迭代器遍歷==============
Key:1000, Value:aaa
Key:30000, Value:ddd
Key:2, Value:bbb
287556納秒
參考:中國大學mooc《java核心技術》