【问题标题】:HashMap internally uses Node<K, V> array vs Hashtable internally uses Map.Entry<K, V> array, Why is this internal difference? [closed]HashMap 内部使用 Node<K, V> 数组 vs Hashtable 内部使用 Map.Entry<K, V> 数组,为什么会有这种内部差异? [关闭]
【发布时间】:2015-02-02 09:01:29
【问题描述】:

HashMap 内部使用Node&lt;K, V&gt; array vs Hashtable 内部使用Map.Entry&lt;K, V&gt; array,为什么会有这种内部差异:

HashMap 使用带有 Map.Entry 实现的 Node 内部类。

static class Node<K,V> implements Map.Entry<K,V> {
    final int hash;
    final K key;
    V value;
    Node<K,V> next;

    Node(int hash, K key, V value, Node<K,V> next) {
        this.hash = hash;
        this.key = key;
        this.value = value;
        this.next = next;
    }

Hashtable 正在使用 Map.Entry。

private static class Entry<K,V> implements Map.Entry<K,V> {
    final int hash;
    final K key;
    V value;
    Entry<K,V> next;

    protected Entry(int hash, K key, V value, Entry<K,V> next) {
        this.hash = hash;
        this.key =  key;
        this.value = value;
        this.next = next;
    }

两者的接缝相同,但它们不同。
是否有任何使用HashMap的具体原因是使用Node&lt;K,V&gt;array而不是Map.Entry&lt;K,V&gt;array

【问题讨论】:

  • 据我所知,这些类之间的唯一区别是它们的名称不同。请注意,Entry&lt;K, V&gt;Map.Entry&lt;K, V&gt; 不同。
  • 这个问题的最后一句话似乎是在问是否有理由使用HashMap而不是Hashtable。答案是:始终使用 HashMap,除非您正在使用需要 Hashtable 实例的 API,因为 Hashtable 是 Java 1.0 的保留,它具有几乎无用的每个方法同步。

标签: java arrays collections hashmap hashtable


【解决方案1】:

两者都使用接口Map.EntryHashTable,在 HashMap 之前提供了它的私有类实现,它只能在 HashTable 类内部访问。因此,在HashMap 中使用它是不可能的。

【讨论】:

    猜你喜欢
    • 2013-04-13
    • 1970-01-01
    • 2021-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-21
    • 1970-01-01
    相关资源
    最近更新 更多