Map Hashtable Hashmap 集合四

Map是通过键值对来唯一标识的,所以不能重复 存相同键值对

Hashtable存的是键值对 Hashtable<key,value> key,value 都不能为null 方法get(); put();

Hashtable<Student,Integer> ht = new Hashtable<Student,Integer>();
ht.put(new Student("s1",10),10); //int自动装箱 Integer
ht.put(new Student("s1",10),10);
ht.put(new Student("s2",20),20);
ht.put(new Student("s3",30),30);
Enumeration<Student> en = ht.keys();  //用枚举遍历键
while(en.hasMoreElements()) {
  Student s = en.nextElement();
  System.out.println(s+" "+ht.get(s)); //用get(key);方法用s取出值
}

Hashtable和Hashmap的不同

Hashtable继承自Dictionary类,Hashmap是Map接口的一个实现类(继承自AbstractMap);

在Hashmap中,null可以作为键,但只能有一个,值可以有多个null

Hashtable中的方法是同步的,Hashmap是不同步的,可以用Map Collections.synchronizedMap(HashMap);返回同步的Hashmap。

原文地址:https://www.cnblogs.com/weixiaole/p/3450744.html