[英]Why does Hashtable use Entry<?,?> internally?
Here's Hashtable#get
: 这是
Hashtable#get
:
@SuppressWarnings("unchecked")
public synchronized V get(Object key) {
Entry<?,?> tab[] = table;
int hash = key.hashCode();
int index = (hash & 0x7FFFFFFF) % tab.length;
for (Entry<?,?> e = tab[index] ; e != null ; e = e.next) {
if ((e.hash == hash) && e.key.equals(key)) {
return (V)e.value;
}
}
return null;
}
Why does it use Entry<?,?>
instead of Entry<K,V>
? 为什么使用
Entry<?,?>
而不是Entry<K,V>
?
Hashtable
's creation predates any work done with generics in Java 1.5, so the likely scenario here was that the generics were retrofitted. Hashtable
的创建早于Java 1.5中使用泛型的任何工作,因此这里可能出现的情况是泛型被改造了。
Although a bigger tell may be due to the fact that table
is an array, and generics and arrays just don't get along well. 虽然更大的说法可能是因为
table
是一个数组,而泛型和数组只是不能很好地相处。
If table
(the field in Hashtable
) were typed, you'd have to deal with a lot of these declarations... 如果
table
(在现场Hashtable
) 的类型,你必须处理很多这些声明...
// Generic array creation!
Entry<K, V>[] newMap = new Entry<K, V>[newCapacity];
...and the likely design/implementation decision was to strive for compatibility as opposed to a full-on embrace of generics. ......可能的设计/实施决策是争取兼容性,而不是全面接受泛型。
Also note that creating an array type with a wildcard will not cause an compile-time error, whereas creating an array with a concrete type will , due to the fact that a generic type with an unbound wildcard is considered reifiable : 另请注意,使用通配符创建数组类型不会导致编译时错误,而创建具有特定类型的数组将会因为带有未绑定通配符的泛型类型被认为是可恢复的 :
List<?>[] foo = new ArrayList[10]; // perfectly legal but not encouraged
List<String> bar = new ArrayList[10]; // not legal
The convention going forward would be to use HashMap
instead, since this particular implementation is both synchronized and still uses a lot of pre-1.5 conventions in it. 未来的惯例将是使用
HashMap
,因为这个特定的实现是同步的,并且仍然在其中使用了许多1.5之前的约定。 (If you want synchronization, even the docs recommend ConcurrentHashMap
.) (如果你想要同步,甚至文档也推荐使用
ConcurrentHashMap
。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.