Sve*_*obs 6 java hashtable hashcode
我想知道Hashtable#hashCode()
当Hashtable
只包含每对具有相同键和值的条目时,Java的默认实现是否被破坏.
请参阅以下应用程序:
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
}
}
Run Code Online (Sandbox Code Playgroud)
空Hashtable的哈希码为0.在将密钥"Test"
和值"Test"
添加到Hastable的条目之后,哈希码仍为 0.
问题是在Hashtable的hashCode()
方法中,计算每个条目的哈希码并将其添加到哈希码中,如下所示
h += e.key.hashCode() ^ e.value.hashCode()
Run Code Online (Sandbox Code Playgroud)
但是XOR
,相同的哈希码(相同的字符串就是这种情况)始终为0.因此具有相同键和值的条目不是Hashtable哈希码的一部分.
由于Hashtable实际上已经发生了变化,因此该实现很难实现.密钥和值是否相同无关紧要.
归档时间: |
|
查看次数: |
501 次 |
最近记录: |