equals是判断两个变量或实例所指向的内存空间的值是不是相同
==是指对内存地址进行比较
equals()是对字符串的内容进行比较
==指引用是否相同
equals()指的是值是否相同
复写equals方法
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + Id;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((sex == null) ? 0 : sex.hashCode());
return result;
}
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) obj;
if (Id != other.Id)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (sex == null) {
if (other.sex != null)
return false;
} else if (!sex.equals(other.sex))
return false;
return true;
}
测试类
@Test
public void equalsStu() {
SessionFactory sessionFactory = null;
Session session = null;
Transaction t = null;
try {
sessionFactory = HibernateUtil.getSession();
session = sessionFactory.getCurrentSession();
t = session.beginTransaction();
User u = (User)session.get(User.class, 1);
User u1 = (User)session.get(User.class, 2);
System.out.println(u.getUsername()==u1.getUsername());
System.out.println(u.getUsername().equals(u1.getUsername()));
} catch (HibernateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}