开发者

Hashing used by Hashtable?

What kind of hashing methodoly is used in Hasht开发者_C百科able implementation in Java?


In Java the Object class defines a method int hashCode(). Each class implements this differently, or not at all. The default implementation is to call System.identityHashCode(this).

Hashtable uses the value returned by hashCode(), but truncates it according to the table size.

By the way, Hashtable is old. If you want to use it, you should use HashMap or ConcurrentHashMap instead.


@Bart is correct, but I wanted to show you how you can discover this from the source code of Hashtable. The source is available here. Search for hash( and you find this function:

119           public int getKeyHash() {
120               return key.hashCode();
121           }

If we look a few lines up, we find that key is any Object:

 89       private static class Entry<K, V> extends MapEntry<K, V> {
 90           Entry<K, V> next;

We then look at a random class such as String and find it has a hashCode() method. We then also look at the Object class to find it also has a hashCode() method. Therefore any object (since they all inherit from Object) has a hashCode() method.

Out of curiosity, we have a look at the source for Object and find this:

 33     public int hashCode() {
 34         return VMMemoryManager.getIdentityHashCode(this);
 35     }

Bingo!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜