基础知识:HashTable和HashMap的区别

   

总结

   

这两个东西一个很重要的区别是Hashtable是线程安全的,而HashMap是线程不安全的。

   

HashMap要实现同步则要通过额外的同步机制:一般Collections的一个静态方法得到解决:Map m = Collections.synchronizedMap(new HashMap(...));

   

这个方法返回一个同步的Map,这个Map封装了底层的HashMap的所有方法,使得底层的HashMap即使是在多线程的环境中也是安全的。

   

另外hashtablekey value都不可以为null,而hashmap可以,HashMap可以用null做为键(当然只能有一个),也允许Null值,可以由一个或多个键对应Null值。

   

另外还有一个不太重要的区别就是Hashtable继承自dictionary类而hashmap继承自map接口

   

测试

   

比如我同样往这两种数据结构中加入2,000,000个同样的字符串,比较其插入的时间

   

117 millis has passed when using HashTable.

42 millis has passed when using HashMap.

   

测试代码

   

public class HashmapAndHashTable {

   

private static final String base = " base string. ";

private static final int count = 2000000;

   

public static void HashmapTest() {

String key="hello";

String value="world";

long begin, end;

begin = System.currentTimeMillis();

HashMap<String, String> hashMap=new HashMap<>();

for (int i = 0; i < count; i++) {

hashMap.put(key, value);

}

end = System.currentTimeMillis();

System.out.println((end - begin)

+ " millis has passed when using HashMap. ");

}

   

public static void hashTableTest() {

String key="hello";

String value="world";

long begin, end;

begin = System.currentTimeMillis();

Hashtable<String, String>hashtable=new Hashtable<>();

for (int i = 0; i < count; i++) {

hashtable.put(key, value);

}

end = System.currentTimeMillis();

System.out.println((end - begin)

+ " millis has passed when using HashTable. ");

}

public static void main(String[] args) {

// TODO Auto-generated method stub

hashTableTest();

HashmapTest();

}

   

}

   

posted @ 2015-05-03 11:06  keedor  阅读(190)  评论(0编辑  收藏  举报