我想知道当Hashtable只包含每对具有相同键和值的条目时,Java的Hashtable#hashCode()的默认实现是否被破坏.
请参阅以下应用程序:
public class HashtableHash { public static void main(final String[] args) { final Hashtable<String,String> ht = new Hashtable<String,String>(); final int h1 = ht.hashCode(); System.out.println(h1); // output is 0 ht.put("Test","Test"); final int h2 = ht.hashCode(); System.out.println(h2); // output is 0 ?!? // Hashtable#hashCode() uses this algorithm to calculate hash code // of every element: // // h += e.key.hashCode() ^ e.value.hashCode() // // The result of XOR on identical hash codes is always 0 // (because all bits are equal) ht.put("Test2","Hello world"); final int h3 = ht.hashCode(); System.out.println(h3); // output is some hash code } }
空Hashtable的哈希码为0.在使用键“Test”并且值“Test”已添加到Hastable的条目之后,哈希码仍为0.
问题是在Hashtable的hashCode()方法中,计算每个条目的哈希码并将其添加到哈希码中,如下所示
h += e.key.hashCode() ^ e.value.hashCode()
但是,相同哈希码的XOR(相同字符串的情况)始终为0.因此具有相同键和值的条目不是Hashtable哈希码的一部分.
由于Hashtable实际上已经发生了变化,因此该实现很难实现.密钥和值是否相同无关紧要.
解决方法
来自
hashCode的文档;
It is not required that if two objects are unequal according to the
equals(java.lang.Object) method,then calling the hashCode method on
each of the two objects must produce distinct integer results.
However,the programmer should be aware that producing distinct
integer results for unequal objects may improve the performance of
hashtables.
换句话说,糟糕的实施 – 也许.破碎 – 不符合规范.