我们对两个对象进行equals比较,其实底层是根据 hashcode 返回的整数值决定的,hashcode的返回值 是根据
由 Object 类定义的 hashCode 方法确实会针对不同的对象返回不同的整数。(这一般是通过将该对象的内部地址转换成一个整数来实现的,但是 JavaTM 编程语言不需要这种实现技巧。)
String 类重写了hashcode方法,是根据字符串返回hashcode,这就意味着只要你输入的两个字符串的字母是相同的,那么它就会返回相同的hashcode,即使这是两个不同的对象。
public int hashCode() {
int h = hash;
if (h == 0 && value.length > 0) {
char val[] = value;
for (int i = 0; i < value.length; i++) {
h = 31 * h + val[i];
}
hash = h;
}
return h;
}
hashcode和 equals方法是绑定在一起的,当我们修改hashcode方法时,我们也会同时修改equals方法。
在我们定义的数据分装类,如果我们不重写 hashcode和equals方法,两个不同的对象会返回false,但是当我们重写hashcode和equals方法,底层可以调用String的hashcode方法,这时只要我们对bean对象中分装的值相同就会返回true
@Test
public void testObject(){
Student stu=new Student();
stu.setId(0);
stu.setName("nike");
stu.setEmail("1233@qq.com");
System.out.println(stu.hashCode());
Student stu1=new Student();
stu1.setId(0);
stu1.setName("nike");
stu1.setEmail("1233@qq.com");
System.out.println(stu1.hashCode());
boolean flag = stu1.equals(stu);
System.out.println(flag);
String str=new String();
}
重写的hashcode和equals方法
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((email == null) ? 0 : email.hashCode());
result = prime * result + id;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Student other = (Student) obj;
if (email == null) {
if (other.email != null)
return false;
} else if (!email.equals(other.email))
return false;
if (id != other.id)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
等于一般对象保存的是对象的引用,及地址,因此只要是两个不同的对象,他们就不会相同。