Why does Hashtable use Entry <?,?> Internally?

Here's the 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 he use Entry<?,?> Instead of Entry<K,V> ?

+7
java collections generics
source share
1 answer

Hashtable creation precedes any work with generics in Java 1.5, so the likely scenario here was that the generics were modified.

Although a larger story may be due to the fact that table is an array, generics and arrays just don't get along well.

If table typed (field in Hashtable ), you will have to deal with a lot of these declarations ...

 // Generic array creation! Entry<K, V>[] newMap = new Entry<K, V>[newCapacity]; 

... and the likely design / implementation solution was a desire for compatibility, not a full-blown generic declaration.

Also note that creating an array type with a wildcard will not cause compile-time errors, while creating an array with a specific type will be due to the fact that a generic type with an unrelated pattern is considered to be renewable :

 List<?>[] foo = new ArrayList[10]; // perfectly legal but not encouraged List<String> bar = new ArrayList[10]; // not legal 

The next convention will be to use HashMap instead, since this particular implementation is synchronized and still uses a lot of preliminary conventions in it. (If you want to sync, even documents recommend ConcurrentHashMap .)

+1
source share

All Articles