为什么重写equals一定要重写hashCode

一.Object类中的equals和hashCode

众所周知,equals和hashCode是java.lang.Object类的两个重要方法,下面这段代码是Object类这两个方法的源码。可以看出,Object类的equals方法就是比较两个对象的内存地址,hashCode方法是本地方法,是根据对象的内存地址经哈希算法得来的。

    public native int hashCode();

    public boolean equals(Object obj) {
        return (this == obj);
    }

二.String类中的equals和hashCode

String类是java中最常用的一个类,重写了Object类的equals方法和hashCode方法,下面这段代码是String类这两个方法的源码。可以看出,String类的equals方法就是比较两个String对象是不是同一个内存对象,或者两个String对象的每个字符都是对应相同的,即逻辑上是相等的,hashCode方法就是用String对象中的每个字符参与运算后得到hash值。

    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;
    }

三.重新认识equals和hashCode

1.equals和hashCode的作用

equals和hashCode的作用其实一样,在Java里都是用来对比两个对象是否相等。

2.equals和hashCode的区别

equals和hashCode的区别主要在于:一个是性能,一个是可靠性。

hashCode方法:因为重写的equals方法一般比较复杂,调用equals方法比较两个对象是否相等效率就比较低。而利用hashCode进行对比,只需要生成一个hash值进行比较就可以了,效率很高。

equals方法:因为hashCode并不是完全可靠,有时候不同的对象生成的hashCode也可能一样(生成hash值的公式可能存在的问题),所以hashCode并不是完全可靠,只能通过equals保证两个对象确实相等。

实际应用:对于需要大量并且快速的对比,如果都用equals去做显然效率太低,所以解决方式是,每当需要对比的时候,先用hashCode去对比,如果hashCode不一样,那这两个对象肯定不相等(也就是不必再用equals去对比了),如果hashCode相等,此时再用equals对比,如果equals也相同,则表示这两个对象确实相同,这样既大大提高了执行效率也保证了对比的可靠性。

如下是两条关于equals和hashCode约定俗成的规则:

  • equals相等的两个对象,他们的hashCode肯定相等
  • hashCode相等的两个对象,他们的equals不一定相等

3.为什么重写equals一定要重写hashCode

如果重写了equals,比如说是基于对象的内容实现的,而没有重写hashCode,就会调用Object类中的hashCode,那么就会导致两个逻辑上相等的对象,hashCode却不一样。这样,当你用其中一个对象作为key保存到HashMap、HashSet或者Hashtable中,再以另一个“相等的”对象作为key去取值,则根本找不到。

因此,为什么重写equals一定要重写hashCode,其实简单来说就是为了保证两个对象在equals相同的情况下hashCode值也必定相同。

4.什么时候需要重写

一般情况下判断两个对象是否相等时不需要重写hashCode,只有当类的对象需要作为HashMap、HashSet或者Hashtable的key时才需要重写hashCode。

四.实例分析

下面是Student类,重写了equals却没有重写hashCode。

public class Student {
    private String name;
    private int age;

    public Student(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;
        Student student = (Student) o;
        return age == student.age &&
                Objects.equals(name, student.name);
    }

    public static void main(String[] args) {
        Map<Student, String> map = new HashMap<Student, String>();
        Student student1 = new Student("tony", 18);
        map.put(student1, "skr");
        Student student2 = new Student("tony", 18);
        System.out.println(map.get(student2));
    }
}

我们看下执行结果,不难理解,student1和student2虽然逻辑上是相等的对象,但是Student类没有重写hashCode,所以它们的hashCode值不相等,所以在map中用student2去取值会返回null。

null

下面在Studen类中加上重写的hashCode。

public class Student {
    private String name;
    private int age;

    public Student(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;
        Student student = (Student) o;
        return age == student.age &&
                Objects.equals(name, student.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }

    public static void main(String[] args) {
        Map<Student, String> map = new HashMap<Student, String>();
        Student student1 = new Student("tony", 18);
        map.put(student1, "skr");
        Student student2 = new Student("tony", 18);
        System.out.println(map.get(student2));
    }
}

再来看执行结果,不难理解,Student类重写的hashCode跟Student类的两个属性有关,所以equals相等的两个Student对象,他们的hashCode肯定相等,所以在map中用student2可以取到值。

skr

参考:
为什么重写equals时必须重写hashCode方法
为什么重写equals一定要重写hashcode?

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。