为什么要重写equals和hashcode

时间:2019-11-11
本文章向大家介绍为什么要重写equals和hashcode,主要包括为什么要重写equals和hashcode使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

  我在最开始遇到这个问题时是很疑惑地,因为我只重写了equals但是并没有出现什么问题。其实首先要明白一点的是重写equals时重写hashcode

并不是java语法层面的问题。而是一种通用约定。因为java中基于散列的集合实现了这个约定。所以当你的类在集合这样的数据结构中使用,也需要遵守这种约定。

不然就会出错。下面是一个例子。

public class EqualsAndHashcode {
    /**
     * 显然 我们的目的是对于name 和 age 相同的对象 都返回的是同一个值
     * @param args
     */
    public static void main(String[] args) {
        Map<Student, String> map = new HashMap<>();
        Student one = new Student("tom", 12);
        map.put(one, "one");
        Student two = new Student("tom", 12);
        System.out.println(map.get(two));
    }
}

class Student {
    String name;
    int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

如果没有重写 equals和hashcode显然 输出的是null.

 @Override
    public boolean equals(Object obj) {
        if (obj == this) {
            return true;
        }
        if (obj instanceof Student) {
            Student student = (Student) obj;
            return student.age==this.age&&student.name.equals(this.name);
        }
        return false;
    }

如果只重写equals 输出的依然是null

 @Override
    public int hashCode() {
        int result = 13;
        result = result * 37 + age;
        result = result * 37 + name.hashCode();
        return result;
    }

重写hashcode之后 ,可以输出one.

public class EqualsAndHashcode {
public static void main(String[] args) {
Map<Student, String> map = new HashMap<>();
Student one = new Student("tom", 12);
map.put(one, "one");
Student two = new Student("tom", 12);
System.out.println(map.get(two));
}
}

class Student {
String name;
int age;

public Student(String name, int age) {
this.name = name;
this.age = age;
}

原文地址:https://www.cnblogs.com/shaomys/p/11834266.html