加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Java Hashtable #hashCode()实现坏了吗?

发布时间:2020-12-14 06:00:38 所属栏目:Java 来源:网络整理
导读:我想知道当Hashtable只包含每对具有相同键和值的条目时,Java的Hashtable#hashCode()的默认实现是否被破坏. 请参阅以下应用程序: public class HashtableHash { public static void main(final String[] args) { final HashtableString,String ht = new Hash
我想知道当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.

换句话说,糟糕的实施 – 也许.破碎 – 不符合规范.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读