Java中HashMap和Hashtable之间的区别是什么?

对于非线程应用程序,哪个更有效?


当前回答

看看这个图表。它提供了不同数据结构之间的比较以及HashMap和Hashtable。比较准确、清晰且易于理解。

Java集合矩阵

其他回答

哈希表:

Hashtable是一种保留键值对值的数据结构。它不允许键和值都为null。如果添加null值,将获得NullPointerException。它是同步的。因此,它有其成本。在特定时间,只有一个线程可以访问HashTable。

例子:

import java.util.Map;
import java.util.Hashtable;

public class TestClass {

    public static void main(String args[ ]) {
    Map<Integer,String> states= new Hashtable<Integer,String>();
    states.put(1, "INDIA");
    states.put(2, "USA");

    states.put(3, null);    //will throw NullPointerEcxeption at runtime

    System.out.println(states.get(1));
    System.out.println(states.get(2));
//  System.out.println(states.get(3));

    }
}

哈希映射:

HashMap类似于Hashtable,但它也接受键值对。它允许键和值都为空。它的性能优于HashTable,因为它是非同步的。

例子:

import java.util.HashMap;
import java.util.Map;

public class TestClass {

    public static void main(String args[ ]) {
    Map<Integer,String> states = new HashMap<Integer,String>();
    states.put(1, "INDIA");
    states.put(2, "USA");

    states.put(3, null);    // Okay
    states.put(null,"UK");

    System.out.println(states.get(1));
    System.out.println(states.get(2));
    System.out.println(states.get(3));

    }
}

我的小贡献:

Hashtable和HashMap之间的第一个也是最重要的区别是,HashMap不是线程安全的,而Hashtable是线程安全的集合。Hashtable和HashMap之间的第二个重要区别是性能,因为HashMap不同步,所以性能比Hashtable好。Hashtable与HashMap的第三个区别是Hashtable是过时的类,应该在Java中使用ConcurrentHashMap代替Hashtable。

除了已经提到的差异之外,应该注意的是,自从Java8以来,HashMap动态地用TreeNodes(红黑树)替换每个bucket中使用的Nodes(链表),因此即使存在高哈希冲突,搜索时最坏的情况也是

HashMap的O(log(n))与Hashtable中的O(n)。

*上述改进尚未应用于Hashtable,而仅应用于HashMap、LinkedHashMap和ConcurrentHashMap。

仅供参考,目前,

TREEIFY_THRESHOLD=8:如果存储桶包含8个以上的节点,则链接列表将转换为平衡树。UNTREEIFY_THRESHOLD=6:当存储桶太小(由于删除或调整大小)时,树将转换回链接列表。

除了izb所说的,HashMap允许空值,而Hashtable不允许。

还要注意,Hashtable扩展了Dictionary类,作为Javadocs状态,该类已过时,已被Map接口取代。

hashtable和hashmap之间的另一个关键区别是,hashmap中的Iterator是快速失败的,而hashtable的枚举器不是快速失败的。如果任何其他线程通过添加或删除Iterator自己的remove()方法以外的任何元素来从结构上修改映射,则抛出ConcurrentModificationException。但这不是一种保证的行为,将由JVM尽最大努力完成。"

我的来源:http://javarevisited.blogspot.com/2010/10/difference-between-hashmap-and.html