为什么对象重写equals方法必须重写hashCode方法

重写equals与hashCode
本文深入探讨了在Java中重写equals方法时为何必须重写hashCode方法,通过示例展示了如何正确实现这两个方法以满足hash一致性,确保在使用如HashMap等数据结构时,equals的对象能正确映射到相同的hash槽位。

前言

我们知道重写equals方法必须重写hashcode方法,此文从一些使用角度分析原因

1. hashCode方法源码

 public class Object {
    /**
     * Returns a hash code value for the object. This method is
     * supported for the benefit of hash tables such as those provided by
     * {@link java.util.HashMap}.
     * <p>
     * The general contract of {@code hashCode} is:
     * <ul>
     * <li>Whenever it is invoked on the same object more than once during
     *     an execution of a Java application, the {@code hashCode} method
     *     must consistently return the same integer, provided no information
     *     used in {@code 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.
     * <li>If two objects are equal according to the {@code equals(Object)}
     *     method, then calling the {@code hashCode} method on each of
     *     the two objects must produce the same integer result.
     * <li>It is <em>not</em> required that if two objects are unequal
     *     according to the {@link java.lang.Object#equals(java.lang.Object)}
     *     method, then calling the {@code 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 hash tables.
     * </ul>
     * <p>
     * As much as is reasonably practical, the hashCode method defined by
     * class {@code Object} does return distinct integers for distinct
     * objects. (This is typically implemented by converting the internal
     * address of the object into an integer, but this implementation
     * technique is not required by the
     * Java&trade; programming language.)
     *
     * @return  a hash code value for this object.
     * @see     java.lang.Object#equals(java.lang.Object)
     * @see     java.lang.System#identityHashCode
     */
    public native int hashCode();

hashCode源码来源于Object类,所有的类都是继承此类,继承hashCode方法,是一个native方法。

看源码注释:

1)多次运算同一个对象的hashCode,结果必须一样

2)两个对象equals,那么hashCode必须一样

3)两个对象not equals,hashCode不一定不一样(不是必须不一样,即hash冲突的可能性)

这是hashCode的定义要求

2. equals方法源码解析

public class Object {
    /**
     * The {@code equals} method for class {@code Object} implements
     * the most discriminating possible equivalence relation on objects;
     * that is, for any non-null reference values {@code x} and
     * {@code y}, this method returns {@code true} if and only
     * if {@code x} and {@code y} refer to the same object
     * ({@code x == y} has the value {@code true}).
     * <p>
     * Note that it is generally necessary to override the {@code hashCode}
     * method whenever this method is overridden, so as to maintain the
     * general contract for the {@code hashCode} method, which states
     * that equal objects must have equal hash codes.
     *
     * @param   obj   the reference object with which to compare.
     * @return  {@code true} if this object is the same as the obj
     *          argument; {@code false} otherwise.
     * @see     #hashCode()
     * @see     java.util.HashMap
     */
    public boolean equals(Object obj) {
        return (this == obj);
    }

equals方法也是Object的方法,所有类继承至此方法,可以重写。源码可以看出==比较,即值比较或内存地址比较

要求:

equals的对象,hashCode必须一样

3. demo

如下示例:Person类

public class TestEquals {
    public static void main(String[] args) {
        Person person = new Person();
        person.setAge(13);
        person.setName("Tom");

        Person person2 = new Person();
        person2.setAge(13);
        person2.setName("Tom");

        System.out.println(person.equals(person2));
        System.out.println(person.hashCode() == person2.hashCode());
    }
}

--------
结果
false
false

可以看出equals的结果均是false,违背了我们的业务需求,因为这两个对象在业务中都是一个人。要实现这个需求必须重写equals方法

3.1 重写equals方法

    public boolean equals(Object person) {
        if (this == person)
            return true;
        if (person instanceof Person){
            Person other = (Person) person;
            if (this.age != other.getAge()){
                return false;
            }

            if (!this.name.equals(other.getName())){
                return false;
            }

            return true;
        }

        return false;
    }

-----------
上面demo的运算结果如下
true
false

 这样写也没问题,达到了我们的目的,但是违背了Object的hashCode的定义原则,在hash存储的数据结构中,就会出现问题,比如hashMap等存储结构。

笔者在面试A公司的时候被问到一个问题,要求自己设计一个对象作为hashMap的key。这个时候非常的关键,两个equals的对象必须存储在相同的hash槽位。此时如果重写equals方法没有重写hashCode方法,就会出现hashMap中我们定义key的对象,出现在不同槽位的现象。

3.2 重写hashCode方法

Object的hashCode使用内存地址hash,不符合我们的要求

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;

        result = prime * result + (((Integer)age == null) ? 0 : ((Integer)age).hashCode());
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        return result;
    }

-----------
示例测试结果
true
true

3.3 深入分析

如果我们使用自定义类作为hashMap的key对象,那么必须重写equals方法和hashCode方法,保证hash一致性。

我们可以看常用作为HashMap的key的类String和Integer的代码看到,它们都重写了这两个方法

String

public final class String
    implements java.io.Serializable, Comparable<String>, CharSequence {
    public boolean equals(Object anObject) {
        if (this == anObject) {
            return true;
        }
        if (anObject instanceof String) {
            String anotherString = (String)anObject;
            int n = value.length;
            if (n == anotherString.value.length) {
                char v1[] = value;
                char v2[] = anotherString.value;
                int i = 0;
                while (n-- != 0) {
                    if (v1[i] != v2[i])
                        return false;
                    i++;
                }
                return true;
            }
        }
        return false;
    }

    public int hashCode() {
        int h = hash;
        if (h == 0 && value.length > 0) {
            char val[] = value;

            for (int i = 0; i < value.length; i++) {
                h = 31 * h + val[i];
            }
            hash = h;
        }
        return h;
    }

Integer 

public final class Integer extends Number implements Comparable<Integer> {
    public boolean equals(Object obj) {
        if (obj instanceof Integer) {
            return value == ((Integer)obj).intValue();
        }
        return false;
    }

    @Override
    public int hashCode() {
        return Integer.hashCode(value);
    }

    /**
     * Returns a hash code for a {@code int} value; compatible with
     * {@code Integer.hashCode()}.
     *
     * @param value the value to hash
     * @since 1.8
     *
     * @return a hash code value for a {@code int} value.
     */
    public static int hashCode(int value) {
        return value;
    }

重写equals时,重写hashCode保证了相同equals时hashCode的一致性,在使用hash算法的存储结构一致性得到保障

另外:使用自定义类作为hashMap的key,尽量保证key的不可变性,避免put的key由于内容的修改造成hashCode计算的变化,需要在key的对象修改后实时的更新hashMap的Entry的存储的槽位。

 

<think> 首先,用户的问题是基于给定的引用材料:"我想了解重写equals方法需要重写hashcode方法的原因"。引用包括四个来源:[^1], [^2], [^3], [^4],这些都讨论了为什么在Java中重写equals方法必须重写hashCode方法。 我的响应需要遵循系统级指令: - 所有行内数学表达式必须使用$...$格式,但在这个上下文中,似乎没有数学表达式,所以可能不需要。 - 独立公式必须使用$$...$$格式并单独成段,同样,可能不适用。 - LaTeX语法正确。 - 使用中文回答。 - 生成相关问题。 - 回答中引用的段落末尾自然地添加引用标识,例如:[^1]。 用户可见层的要求: - 回答结构清晰,帮助用户逐步解决问题。 - 尽量保证回答真实可靠。 关键点:用户想知道重写equals方法需要重写hashCode方法的原因。引用材料提供了原因: - [^1] 提到了hashCode重写的基本规则和两者之间的关系。 - [^2] 讨论了==与equals的区别,以及为什么必须重写hashCode。 - [^3] 强调违反了Java的对象契约如果不重写hashCode。 - [^4] 提供了一个代码示例,显示如果不重写hashCode,会导致不一致的行为。 核心原因总结自引用: 1. **一致性**:equals方法定义了对象内容的相等性;hashCode方法返回对象的哈希码。在Java中,如果两个对象根据equals方法相等,它们的hashCode必须相等。如果不遵守这个规则,在使用基于哈希的集合(如HashMap、HashSet),会导致问题。 2. **契约**:Java的Object类定义了equalshashCode方法的契约。重写equals方法必须重写hashCode以维持这个契约。 3. **问题示例**:如果只重写equals而不重写hashCode,两个对象可能equalshashCode不同。这会导致在HashMap中,对象可能被放入错误的桶中,无法正常查找或导致重复添加。 结构响应: - **逐步解决**:从基础开始解释,逐步到原因。 - **引用**:在解释,自然地添加引用标识。 - **中文回答**:整个响应用中文。 - **生成相关问题**:在回答后添加相关问题部分。 响应大纲: 1. **引言**:简要介绍equalshashCode方法的作用。 2. **原因解释**: - 解释equals方法重写规则。 - 解释为什么需要一致性。 - 给出基于引用的具体原因。 3. **代码示例**:类似[^4],提供一个简单例子说明问题。 4. **总结**:强调重写的必要性。 5. **相关问题**:生成2-3个相关问题。 相关问题灵感: - 基于主题,如:如何正确重写hashCode方法?如果不重写hashCode会有什么后果?在哪些场景下必须重写hashCode? 确保真实可靠:基于提供的引用和Java官方文档知识。 最终响应要用中文。 </think> ### 重写equals方法必须重写hashCode方法的原因 在Java中,`equals`方法用于比较两个对象的内容是否相等,而`hashCode`方法返回对象的哈希码值。根据Java的对象契约(Object Contract),重写`equals`方法必须同重写`hashCode`方法,否则会导致程序行为异常。主要原因包括以下几点: 1. **维持对象契约的一致性**: Java的`Object`类定义了`equals`和`hashCode`方法之间的契约:如果两个对象根据`equals`方法相等,那么它们的`hashCode`必须相等。反之,如果两个对象的`hashCode`不等,则它们一定不相等。如果不遵守这个规则,会违反Java的通用约定,导致哈希相关集合(如`HashMap`、`HashSet`)工作不正常[^3]。 - 例如,在`HashMap`中,对象存储和检索依赖于`hashCode`值来决定桶的位置。如果只重写`equals`而不重写`hashCode`,两个内容相等的对象可能产生不同的哈希码结果,造成对象无法被正确查找或重复存储。 2. **防止哈希相关集合的异常行为**: 在使用基于哈希的数据结构,`hashCode`方法用于快速定位对象。如果只重写`equals`方法而不重写`hashCode`,会导致以下问题: - **对象丢失**:在`HashSet`中,两个`equals`相等的对象可能被分配到不同的桶中,导致集合无法识别它们是相同的对象,从而允许重复添加。 - **检索失败**:在`HashMap`中,尝试用键对象检索值,如果键的`hashCode`与存储不匹配,即使`equals`返回`true`,也可能无法找到对应的值,引发逻辑错误[^1][^2]。 ```java // 示例:只重写equals而不重写hashCode的问题场景 import java.util.HashSet; public class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Person person = (Person) o; return age == person.age && Objects.equals(name, person.name); } // 错误:没有重写hashCode public static void main(String[] args) { Person p1 = new Person("Alice", 30); Person p2 = new Person("Alice", 30); System.out.println(p1.equals(p2)); // 输出 true HashSet<Person> set = new HashSet<>(); set.add(p1); System.out.println(set.contains(p2)); // 可能输出 false,因为hashCode重写,哈希码不同 } } ``` 3. **确保equalshashCode的逻辑等价性**: `hashCode`方法应基于对象中用于`equals`比较的属性计算哈希码。如果只重写`hashCode`而不重写`equals`,或反之,会导致不一致: - 两个对象`equals`相等,但`hashCode`不同:违反契约,引发哈希集合故障。 - 两个对象`hashCode`相同,但`equals`不相等:这是允许的(哈希冲突),但如果不重写`equals`,可能无法正确处理冲突[^4]。 正确的实践是使用相同的属性集计算哈希码,例如通过`Objects.hash()`方法简化实现,确保两者逻辑一致[^3][^4]。 总结来说,重写`equals`必须重写`hashCode`,是为了遵守Java的对象契约,避免在哈希相关集合中出现不可预测的行为。推荐使用IDE(如IntelliJ IDEA)自动生成`equals`和`hashCode`方法,或利用`Objects.equals()`和`Objects.hash()`来简化代码并提高健壮性[^3][^4]。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值