为何重写equals必定要重写hashCode?

你们都知道,equals和hashcode是java.lang.Object类的两个重要的方法,在实际应用中经常须要重写这两个方法,但至于为何重写这两个方法不少人都搞不明白,如下是个人一些我的理解。java

这是Object类关于这两个方法的源码,能够看出,Object类默认的equals比较规则就是比较两个对象的内存地址。而hashcode是本地方法,java的内存是安全的,所以没法根据散列码获得对象的内存地址,但实际上,hashcode是根据对象的内存地址经哈希算法得来的。算法

public native int hashCode();
public boolean equals(Object paramObject){
    return (this==paramObject);
}

上图展现了Student类的重写后的equals方法和hashcode方法,建议你们用eclipse自动生成,尽可能不要本身敲由于颇有可能会出错。安全

如今有两个Student对象:eclipse

Student s1=new Student("小明",18);ide

Student s2=new Student("小明",18);this

此时s1.equals(s2)必定返回truespa

/*
 * 
 * 
 * equals的使用
 * 
 * */
package com.tinaluo.java;

import java.awt.Color;

class Cat {
    private String name;
    private int age;
    private double weight;
    private Color color;

    public Cat(String name, int age, double weight, Color color) {
        this.name = name;
        this.age = age;
        this.weight = weight;
        this.color = color;
    }

    /*
     * equals改写后必须重写hashCode()方法,对象相同则hashCode必须相同!
     * 一、equals()相同,则hashCode必须相等
     * 二、hashCode不相同等,则equals()必不相等
     * 
     * @see java.lang.Object#hashCode()
     */
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + age;
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        return result;
    }
    @Override
    public boolean equals(Object obj) {
        if(this==obj){
            return true;
        }
        if(obj==null){
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        Cat cat = (Cat) obj;
        return name.equals(cat.name) && (age == cat.age)
                && (weight == cat.weight) && (color.equals(cat.color));
    }
}

public class InternalLoad {
    public static void main(String[] args) {
        Cat a = new Cat("java", 12, 21, Color.BLACK);
        Cat b = new Cat("C++", 12, 21, Color.WHITE);
        Cat c = new Cat("java", 12, 21, Color.BLACK);
        System.out.println(a.equals(b));
        System.out.println(a.equals(c));
        System.out.println(a.hashCode() == c.hashCode());
    }
}

假如只重写equals而不重写hashcode,那么Student类的hashcode方法就是Object默认的hashcode方法,因为默认的hashcode方法是根据对象的内存地址经哈希算法得来的,显然此时s1!=s2,故二者的hashcode不必定相等。code

然而重写了equals,且s1.equals(s2)返回true,根据hashcode的规则,两个对象相等其哈希值必定相等,因此矛盾就产生了,所以重写equals必定要重写hashcode,并且从Student类重写后的hashcode方法中能够看出,重写后返回的新的哈希值与Student的两个属性有关。对象

如下是关于hashcode的一些规定:blog

关键结论:

两个对象相等,hashcode必定相等
两个对象不等,hashcode不必定不等
hashcode相等,两个对象不必定相等
hashcode不等,两个对象必定不等

相关文章
相关标签/搜索