首页 > 其他分享 >重写equals就需要重写hashCode

重写equals就需要重写hashCode

时间:2022-11-25 15:58:44浏览次数:34  
标签:code name equals hashCode Student 重写 id

重写equals不重写hashCode

public class Student {
    private Long id;
    private String code;
    private String name;

    public Student(Long id, String code, String name) {
        this.id = id;
        this.code = code;
        this.name = name;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Student student = (Student) o;
        return Objects.equals(id, student.id) &&
                Objects.equals(code, student.code) &&
                Objects.equals(name, student.name);
    }

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

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", code='" + code + '\'' +
                ", name='" + name + '\'' +
                '}';
    }

 

 

    public static void main(String[] args) {

        Map<Student, String> map = new HashMap<>(16);
        Student stu1 = new Student(1L, "001", "one");
        Student stu2 = new Student(1L, "001", "one");
        map.put(stu1, "one");
        map.put(stu2, "two");
        System.out.println("map.toString():" + map.toString());
    }

结果两个map都打印出来了

map.toString():{Student{id=1, code='001', name='one'}=two, Student{id=1, code='001', name='one'}=one}

 

 

原因:Studeng类没有重写hashCode, Map就会默认找到Object类的hashCode方法去执行,判断内存地址是否一致,因为地址不一致,故报错。

总结:如果重写了equals就必须重写hashCode,如果不重写就会引起与散列集合(HashMap、HashSet、HashTable、ConcurrentHashMap)的冲突。

标签:code,name,equals,hashCode,Student,重写,id
From: https://www.cnblogs.com/zhougongjin/p/16925396.html

相关文章