As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center提供指导。




9年前关闭。




我想知道Hashtable#hashCode()仅包含每对具有相同键和值的条目时,Java的Hashtable的默认实现是否被破坏。

例如,请参阅以下应用程序:

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散列码的一部分。

由于哈希表实际上已更改,因此该实现被打破。键和值是否相同并不重要。

最佳答案

hashCode上的文档中获得;



换句话说,不好的执行-也许。损坏-不符合规范。

10-04 22:54
查看更多