ORM框架入门实例3

重写equals()以及hashCode()

1.使用IDEA工具自动重写User.java中的equals()hashCode()

或在User.java中添加如下代码:

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        User user = (User) o;
        return id == user.id &&
                age == user.age &&
                Objects.equals(name, user.name) &&
                Objects.equals(gender, user.gender) &&
                Objects.equals(birthday, user.birthday);
    }
    @Override
    public int hashCode() {
        return Objects.hash(id, name, gender, age, birthday);
    }

2.在UserDao.java中测试equals()方法和hashCode()方法

    public static void main(String[] args) {
        User u1 = new User();
        u1.setId(1814010924);
        u1.setName("sxz");
        u1.setGender("男");

        User u2 = new User();
        u2.setId(1814010924);
        u2.setName("sxz");
        u2.setGender("男");

        System.out.println("== :"+ ( u1==u2 ));
        System.out.println("equals :" + u1.equals(u2));
        System.out.println("hashCode :" + ( u1.hashCode()==u2.hashCode() ));
    }

3.测试结果:ORM框架入门实例3

上一篇:从入门到入土-基础篇-1


下一篇:Java 对象字段属性差异对比工具类 (修改前&修改后的属性值)