RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / 问题 / 975678
Accepted
Петровченко Иван
Петровченко Иван
Asked:2020-04-28 02:05:41 +0000 UTC2020-04-28 02:05:41 +0000 UTC 2020-04-28 02:05:41 +0000 UTC

hashCode() 和 equals() 以及我的例子

  • 772

我阅读了一篇关于 Habré 的文章,以下是我的示例和信息:

我的代码:

public class Man {

    private String noseSize;
    private String eyesColor;
    private String haircut;
    private boolean scars;
    private int dnaCode;

    public Man(String noseSize, String eyesColor, String haircut, boolean scars, int dnaCode) {
        this.noseSize = noseSize;
        this.eyesColor = eyesColor;
        this.haircut = haircut;
        this.scars = scars;
        this.dnaCode = dnaCode;
    }
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Man man = (Man) o;
        return dnaCode == man.dnaCode;
    }
//геттеры сеттеры и тд

首先,为避免混淆,让我们定义一些术语。相同对象是具有相同字段内容的同一类的对象。

对于同一个对象,哈希码总是相同的;

public class Test {
    public static void main(String[] args) {
        Man man1 = new Man("Большой", "Зеленый", "Горшок", true, 13);
        Man man2 = new Man("Большой", "Зеленый", "Горшок", true, 13);
        System.out.println(man1.hashCode());
    }
}

好的,这里一切都正确,它重新启动多少次显示相同的哈希码,让我们继续:

如果对象相同,则哈希码相同

public class Test {
    public static void main(String[] args) {
        Man man1 = new Man("Большой", "Зеленый", "Горшок", true, 13);
        Man man2 = new Man("Большой", "Зеленый", "Горшок", true, 13);
        System.out.println(man1.hashCode() + "  " + man2.hashCode());
    }
}

控制台输出:1802598046 659748578 为什么这里有两个相同的哈希码?继续前行:

如果哈希码相等,则输入特征并不总是相等(碰撞)

不幸的是,目前我不知道如何获得两个相同的哈希码,所以我无法检查它。我不会介意一个例子。

如果哈希码不同,则保证对象不同;我再次回到这个哈希码不同但对象相同的示例,这就是控制台中显示的内容:

1802598046  659748578



 public class Test {
        public static void main(String[] args) {
            Man man1 = new Man("Большой", "Зеленый", "Горшок", true, 13);
            Man man2 = new Man("Большой", "Зеленый", "Горшок", true, 13);
            System.out.println(man1.hashCode() + "  " + man2.hashCode());
        }
    }
java
  • 1 1 个回答
  • 10 Views

1 个回答

  • Voted
  1. Best Answer
    Stranger in the Q
    2020-04-28T02:22:38Z2020-04-28T02:22:38Z

    你在这里还是有点迷茫

    对于同一个对象,哈希码总是相同的;

    默认情况下,为相同的hashCode对象返回相同的值,但不为相同的对象返回。

    是您自己同意您希望将相同的对象视为相同的对象,为此您必须重新定义equals并相应hashCode地,然后行为将如您正在阅读的文章中所述。

    如果你阅读了hashcode方法的javadoc ,你会发现通常hashcode是一个对象在堆上的地址,转换成一个整数(Integer)

    在合理可行的情况下,由 Object 类定义的 hashCode 方法确实为不同的对象返回不同的整数。(这通常通过将对象的内部地址转换为整数来实现,但 JavaTM 编程语言不需要这种实现技术。)

    考虑到这些方法 (equals()和hashСode()) 在整个 Java 集合中用于确定对象的等价性,这一点非常重要。此外,提供一个好的函数是非常重要的hashСode(),否则可能会发生不必要的碰撞。例如,如果函数不好hashСode(),里面的对象HashMap会更多地出现在一个篮子里,这会降低该篮子中键搜索的整体 HashMap性能,虽然有一个针对此的内置保护机制

    jdk1.8.0_131\src.zip!\java\util\HashMap.java

    /**
     * Computes key.hashCode() and spreads (XORs) higher bits of hash
     * to lower.  Because the table uses power-of-two masking, sets of
     * hashes that vary only in bits above the current mask will
     * always collide. (Among known examples are sets of Float keys
     * holding consecutive whole numbers in small tables.)  So we
     * apply a transform that spreads the impact of higher bits
     * downward. There is a tradeoff between speed, utility, and
     * quality of bit-spreading. Because many common sets of hashes
     * are already reasonably distributed (so don't benefit from
     * spreading), and because we use trees to handle large sets of
     * collisions in bins, we just XOR some shifted bits in the
     * cheapest possible way to reduce systematic lossage, as well as
     * to incorporate impact of the highest bits that would otherwise
     * never be used in index calculations because of table bounds.
     */
    static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }
    

    在你的例子中

     Man man1 = new Man("Большой", "Зеленый", "Горшок", true, 13);
     Man man2 = new Man("Большой", "Зеленый", "Горшок", true, 13);
    

    属性组成相同但实例不同的对象(如双胞胎兄弟)

    如果重新定义equals()并且hashСode()适当,那么这些对象将被视为一个对象。

    public class Man {
    
        private String noseSize;
        private String eyesColor;
        private String haircut;
        private boolean scars;
        private int dnaCode;
    
        public Man(String noseSize, String eyesColor, String haircut, boolean scars, int dnaCode) {
            this.noseSize = noseSize;
            this.eyesColor = eyesColor;
            this.haircut = haircut;
            this.scars = scars;
            this.dnaCode = dnaCode;
        }
    
        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
    
            Man man = (Man) o;
    
            if (scars != man.scars) return false;
            if (dnaCode != man.dnaCode) return false;
            if (noseSize != null ? !noseSize.equals(man.noseSize) : man.noseSize != null) return false;
            if (eyesColor != null ? !eyesColor.equals(man.eyesColor) : man.eyesColor != null) return false;
            return haircut != null ? haircut.equals(man.haircut) : man.haircut == null;
        }
    
        @Override
        public int hashCode() {
            int result = noseSize != null ? noseSize.hashCode() : 0;
            result = 31 * result + (eyesColor != null ? eyesColor.hashCode() : 0);
            result = 31 * result + (haircut != null ? haircut.hashCode() : 0);
            result = 31 * result + (scars ? 1 : 0);
            result = 31 * result + dnaCode;
            return result;
        }
    }
    

    PS:体面的 IDE 具有帮助生成此代码的功能。

    我使用IntellijIdea 社区,他们在那里做Alt+Insert>equals() and hashCode()

    • 4

相关问题

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    根据浏览器窗口的大小调整背景图案的大小

    • 2 个回答
  • Marko Smith

    理解for循环的执行逻辑

    • 1 个回答
  • Marko Smith

    复制动态数组时出错(C++)

    • 1 个回答
  • Marko Smith

    Or and If,elif,else 构造[重复]

    • 1 个回答
  • Marko Smith

    如何构建支持 x64 的 APK

    • 1 个回答
  • Marko Smith

    如何使按钮的输入宽度?

    • 2 个回答
  • Marko Smith

    如何显示对象变量的名称?

    • 3 个回答
  • Marko Smith

    如何循环一个函数?

    • 1 个回答
  • Marko Smith

    LOWORD 宏有什么作用?

    • 2 个回答
  • Marko Smith

    从字符串的开头删除直到并包括一个字符

    • 2 个回答
  • Martin Hope
    Alexandr_TT 2020年新年大赛! 2020-12-20 18:20:21 +0000 UTC
  • Martin Hope
    Alexandr_TT 圣诞树动画 2020-12-23 00:38:08 +0000 UTC
  • Martin Hope
    Air 究竟是什么标识了网站访问者? 2020-11-03 15:49:20 +0000 UTC
  • Martin Hope
    Qwertiy 号码显示 9223372036854775807 2020-07-11 18:16:49 +0000 UTC
  • Martin Hope
    user216109 如何为黑客设下陷阱,或充分击退攻击? 2020-05-10 02:22:52 +0000 UTC
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0000 UTC
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0000 UTC
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0000 UTC
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0000 UTC
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0000 UTC

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

  • 主页
  • 问题
    • 热门问题
    • 最新问题
  • 标签
  • 帮助

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5