HashMap是Hashtable都是实现Map接口。
区别:
1 HashMap不是线程安全的
hastmap是一个接口 是map接口的子接口,是将键映射到值的对象,其中键和值都是对象,并且不能包含重复键,但可以包含重复值。HashMap允许null key和null value,而hashtable不允许。
2 HashTable是线程安全的一个Collection。
HashTable是JDK1.1时的产物。现在基本不用了!- //import java.lang.*;
- import java.util.Hashtable;
- import java.util.Enumeration;
- public class HashApp{
- public static void main(String args[]){
- Hashtable hash=new Hashtable(2,(float)0.8);
- //创建了一个哈希表的对象hash,初始容量为2,装载因子为0.8
- hash.put("Jiangsu","Nanjing");
- //将字符串对象“Jiangsu”给定一关键字“Nanjing”,并将它加入hash
- hash.put("Beijing","Beijing");
- hash.put("Zhejiang","Hangzhou");
- System.out.println("The hashtable hash1 is: "+hash);
- System.out.println("The size of this hash table is"+hash.size());
- //打印hash的内容和大小
- Enumeration enum1=hash.elements();
- System.out.print("The element of hash is: ");
- while(enum1.hasMoreElements())
- System.out.print(enum1.nextElement()+" ");
- System.out.println();
- //依次打印hash中的内容
- if(hash.containsKey("Jiangsu"))
- System.out.println("The capatial of Jiangsu is"+hash.get("Jiangsu"));
- hash.remove("Beijing");
- //删除关键字Beijing对应对象
- System.out.println("The hashtable hash2 is: "+hash);
- System.out.println("The size of this hash table is"+hash.size());
- }
- }
复制代码 运行结果:
The hashtable hash1 is: {Beijing=Beijing, Zhejiang=Hangzhou,Jiangsu=Nanjing}
The size of this hash table is 3
The element of hash is: Beijing Hangzhou Nanjing
The capatial of Jiangsu is Nanjing
The hashtable hash2 is: {Zhejiang=Hangzhou,Jiangsu=Nanjing}
The size of this hash table is 2 |