Object类中 equals方法和hashCode方法的作用!

起源

先来看看 object里面的两个方法的代码块

/**
     * Indicates whether some other object is "equal to" this one.
     * <p>
     * The {@code equals} method implements an equivalence relation
     * on non-null object references:
     * <ul>
     * <li>It is <i>reflexive</i>: for any non-null reference value
     *     {@code x}, {@code x.equals(x)} should return
     *     {@code true}.
     * <li>It is <i>symmetric</i>: for any non-null reference values
     *     {@code x} and {@code y}, {@code x.equals(y)}
     *     should return {@code true} if and only if
     *     {@code y.equals(x)} returns {@code true}.
     * <li>It is <i>transitive</i>: for any non-null reference values
     *     {@code x}, {@code y}, and {@code z}, if
     *     {@code x.equals(y)} returns {@code true} and
     *     {@code y.equals(z)} returns {@code true}, then
     *     {@code x.equals(z)} should return {@code true}.
     * <li>It is <i>consistent</i>: for any non-null reference values
     *     {@code x} and {@code y}, multiple invocations of
     *     {@code x.equals(y)} consistently return {@code true}
     *     or consistently return {@code false}, provided no
     *     information used in {@code equals} comparisons on the
     *     objects is modified.
     * <li>For any non-null reference value {@code x},
     *     {@code x.equals(null)} should return {@code false}.
     * </ul>
     * <p>
     * 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);
    }
/**
     * 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();

注意equals方法上面的一段话:
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.
请注意,只要此方法被覆盖,通常有必要覆盖{@code hash Code}
方法,才可保持{@code hash Code}方法的正确性,其中规定相等的对象必须具有相等的哈希码。
也就是说:
等价的两个对象散列值一定相同,但是散列值相同的两个对象不一定等价,这是因为计算哈希值具有随机性,两个值不同的对象可能计算出相同的哈希值。 在覆盖 equals() 方法时应当总是覆盖 hashCode() 方法,保证等价的两个对象哈希值也相等。HashSet 和 HashMap 等集合类使用了 hashCode() 方法来计算对象应该存储的位置, 因此要将对象添加到这些集合类中,需要让对应的类实现 hashCode() 方法。

验证

实操写段代码就知道了:

public class Example {
    private int id;

//    @Override
//    public int hashCode() {
//        return id;
//    }

    @Override
    public boolean equals(Object obj) {
        if (obj.getClass() == Example.class) {
            return id == ((Example) obj).id;
        }
        return false;
    }

    public Example(int id) {
        this.id = id;
    }

    public static void main(String[] args) {
        Example e1 = new Example(1);
        Example e2 = new Example(1);

        System.out.println(e1.equals(e2));   //true
        System.out.println(e1 == e2);        //false
        System.out.println(e1.hashCode() == e2.hashCode());   //false
    }
}

可以看到 ,重写了equals方法,已经可以让两个 对象调用equals的时候返回true了。
但是还有个问题 ,为什么要重写hashCode方法呢
这就牵涉到HashMap HashSet两个集合类了
因为HashMap 和 HashSet存元素进去的时候,是利用该元素的hashCode()方法去判断该元素应该放置在什么位置。
试想一下,如果一个类没有重写hashCode方法,那么取Object的hashCode方法,存到HashMap或者HashSet的时候会是什么混乱的情况?

public class Example {
    private int id;

    @Override
    public boolean equals(Object obj) {
        if (obj.getClass() == Example.class) {
            return id == ((Example) obj).id;
        }
        return false;
    }

    public Example(int id) {
        this.id = id;
    }

    public static void main(String[] args) {
        Example e1 = new Example(1);
        Example e2 = new Example(1);

        System.out.println(e1.equals(e2));   //true
        System.out.println(e1 == e2);        //false
        System.out.println(e1.hashCode() == e2.hashCode());   //false
        
        HashSet<Example> set = new HashSet<>();
        set.add(e1);
        set.add(e2);
        System.out.println(set.size());   //2
    }
}

这段代码运行结果是2, 这就出现问题了,明明 e1.equals(e2) == true,说明这两个元素是相等的。那么存到HashSet里面就应该是只有一个元素,因为存第二个元素会将它覆盖掉。
但是这段代码却有2个元素。
只要重写该类的hashCode方法,让e1.equals(e2)的同时,hashCode也相等,就可以了。

    @Override
    public int hashCode() {
        return id;
    }

这样再去运行上一段代码,就只有一个元素了。
在这里插入图片描述

结论

也就是说,如果写代码的时候,需要把一些自定义的类加入到HashSet 、HashMap集合中的话,就需要重写它的equals方法和 hashCode方法。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值