当我覆盖equals()方法时,为什么要覆盖hashCode()? [英] Why should I override hashCode() when I override equals() method?

查看:117
本文介绍了当我覆盖equals()方法时,为什么要覆盖hashCode()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我从许多地方和消息来源得知,每当我覆盖equals()方法时,我都需要覆盖hashCode()方法。但请考虑以下代码

Ok, I have heard from many places and sources that whenever I override the equals() method, I need to override the hashCode() method as well. But consider the following piece of code

package test;

public class MyCustomObject {

    int intVal1;
    int intVal2;

    public MyCustomObject(int val1, int val2){
        intVal1 = val1;
        intVal2 = val2;
    }

    public boolean equals(Object obj){
        return (((MyCustomObject)obj).intVal1 == this.intVal1) && 
                (((MyCustomObject)obj).intVal2 == this.intVal2);
    }

    public static void main(String a[]){
        MyCustomObject m1 = new MyCustomObject(3,5);
        MyCustomObject m2 = new MyCustomObject(3,5);
        MyCustomObject m3 = new MyCustomObject(4,5);

        System.out.println(m1.equals(m2));
        System.out.println(m1.equals(m3));
    }
}

这里的输出是真的,假的完全是我的方式想要它,我根本不关心覆盖hashCode()方法。这意味着hashCode()覆盖是一个选项,而不是每个人都说的强制性。

Here the output is true, false exactly the way I want it to be and I dont care of overriding the hashCode() method at all. This means that hashCode() overriding is an option rather being a mandatory one as everyone says.

我想要第二次确认。

推荐答案

它适用于您,因为您的代码不使用任何需要 hashCode() API

It works for you because your code does not use any functionality (HashMap, HashTable) which needs the hashCode() API.

但是,您不知道您的课程(可能不是一次性写入)将在以后调用确实使用其对象作为哈希键的代码,在这种情况下,事情将受到影响。

However, you don't know whether your class (presumably not written as a one-off) will be later called in a code that does indeed use its objects as hash key, in which case things will be affected.

根据对象类的文档


hashCode的一般合约是:

The general contract of hashCode is:


  • 每当调用它时在执行Java应用程序期间,在同一个对象上不止一次,hashCode方法必须始终返回相同的对象整数,前提是没有修改用于对象的等比较的信息。从应用程序的一次执行到同一应用程序的另一次执行,此整数不需要保持一致。

  • Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.

如果两个对象根据等于(Object)方法,然后在两个对象中的每一个上调用hashCode方法必须产生相同的整数结果

这篇关于当我覆盖equals()方法时,为什么要覆盖hashCode()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆