Java中HashMap和HashTable区别

        前几天被一家公司电面的时候被问到HashMap和HashTable的区别,当时就懵逼了,hashTable是个啥?历来没用过啊,因而电面完以后立刻google了一把,这回涨姿式了;java

        HashMap和HashTable同属于Java.util包下的集合类,Hashtable是个过期的集合类,存在于Java API中好久了。在Java 4中被重写了,实现了Map接口,因此自此之后也成了Java集合框架中的一部分。安全

        HashMap和Hashtable都实现了Map接口,但决定用哪个以前先要弄清楚它们之间的分别。主要的区别有:线程安全性,同步(synchronization),以及速度。多线程

对比项 HashMap HashTable
是否线程安全
是否synchronized
是否支持多线程共享 在有正确的同步机制的前提下能够支持多线程共享 支持
单线程效率
只随时间推移元素次序是否不变 不必定
是否支持null的key和value 支持 不支持



        另外一个区别是HashMap的迭代器(Iterator)是fail-fast迭代器,而Hashtable的enumerator迭代器不是fail-fast的。因此当有其它线程改变了HashMap的结构(增长或者移除元素),将会抛出ConcurrentModificationException,但迭代器自己的remove()方法移除元素则不会抛出ConcurrentModificationException异常。但这并非一个必定发生的行为,要看JVM。这条一样也是Enumeration和Iterator的区别。app

        Java 5提供了ConcurrentHashMap,它是HashTable的替代,比HashTable的扩展性更好。同时HashMap也能够经过如下方式进行同步操做,返回的Map就是一个框架

HashMap<String, String> hashMap = new HashMap<String, String>();
Map map = Collections.synchronizedMap(hashMap);
*****synchronizedMap的方法API描述*****
Returns a synchronized (thread-safe) map backed by the specified map. In order 
to guarantee serial access, it is critical that all access to 
the backing map is accomplished through the returned map.It is imperative that the user manually synchronize on the returned map when 
iterating over any of its collection views:
  Map m = Collections.synchronizedMap(new HashMap());
      ...
  Set s = m.keySet();  // Needn't be in synchronized block
      ...
  synchronized(m) {  // Synchronizing on m, not s!
      Iterator i = s.iterator(); // Must be in synchronized block
      while (i.hasNext())
          foo(i.next());
  } 
Failure to follow this advice may result in non-deterministic behavior.The returned map will be serializable if the specified map is serializable.
Parameters:
m the map to be "wrapped" in a synchronized map.
Returns:
a synchronized view of the specified map.

        通常的话仅在须要 彻底的线程安全的时候使用Hashtable,而若是你使用Java 5或以上的话,请使用ConcurrentHashMap代替HashTable;this

相关文章
相关标签/搜索