欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java重写equals,hashcode

程序员文章站 2024-03-22 17:46:40
...

重写equals,hashcode

public class User {
    private int id;
    private String name;
    private String gender;
    private int age;
    private Date birthday;

    @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);
    }
try{
        sf = HibernateUtil.getSessionFactory();
        session = sf.getCurrentSession();
        ts = session.beginTransation();
        
        u1 = session.get(User.class, 35);
        session.evict(u1);
        u2 = session.get(User.class,35);

        System.out.println("u1 == u2:\t" + (u1 == u2));
        System.out.println("u1.equals(u2):\t" + u1.equals(u2));
        System.out.println("u1.hashcode:\t" + u1.hashCode());
        System.out.println("u2.hashcode:\t" + u2.hashCode());
        ts.commit();
    }catch(Exception e)

执行

Java重写equals,hashcode