【发布时间】:2015-02-02 09:01:29
【问题描述】:
HashMap 内部使用Node<K, V> array vs Hashtable 内部使用Map.Entry<K, V> 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<K,V>array而不是Map.Entry<K,V>array?
【问题讨论】:
-
据我所知,这些类之间的唯一区别是它们的名称不同。请注意,
Entry<K, V>与Map.Entry<K, V>不同。 -
这个问题的最后一句话似乎是在问是否有理由使用HashMap而不是Hashtable。答案是:始终使用 HashMap,除非您正在使用需要 Hashtable 实例的 API,因为 Hashtable 是 Java 1.0 的保留,它具有几乎无用的每个方法同步。
标签: java arrays collections hashmap hashtable