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

19 篇文章 0 订阅
10 篇文章 0 订阅

前言

我们知道重写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的存储的槽位。

 

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值