理论
Object类的equals()特点
自反省:x.equals(x)返回真;
对称性:x.equals(y)返回真,那么y.equals(x)也返回真
传递性:x.equals(y)返回真,y.equals(z)返回真,那么x.equals(z)也返回真
一致性:x.equals(y)第一次调用返回真,那么不管调用多少次都应该返回真,
前提是x和y不修改
对于非空引用x:x.equals(null),都返回false
Object类的hashCode()的特点
如果我们重写了equals(),那么也需要重写hashCode(),反之亦然
在Java应用程序一次执行过程当中,对于同一个对象的hashCode()的多次调用,
他们应该返回同样的值(前提是该对象的信息没有发生变化)
对于两个对象来说,
如果使用equals()返回true,则hashCode值一定相同
如果使用equals()返回false,则hashCode可以相同也可以不同,不同的话则可以提高性能
对于Object来说,不同Object对象的hashCode值是不相同的,
因为Object类的hashCode值表示的是对象的地址
案例
import java.util.HashSet;
import java.util.Set;
public class MyHashSet {
public static void main(String[] args) {
Set<Person> set1 = new HashSet<Person>();
set1.add(new Person("lwc"));
set1.add(new Person("lwc"));
System.out.println(set1);// 增加个两
// String也重写了equals()和hashCode()
Set<String> set2 = new HashSet<String>();
set2.add(new String("aaa"));
set2.add(new String("aaa"));
System.out.println(set2);// 增加一个
// 重写了equals()和hashCode()
Set<Student> set3 = new HashSet<Student>();
set3.add(new Student("lwc"));
set3.add(new Student("lwc"));
System.out.println(set3);// 增加一个
}
}
class Person {
String name;
public Person(String name) {
this.name = name;
}
}
class Student {
String name;
public Student(String name) {
this.name = name;
}
@Override
public int hashCode() {
return this.name.hashCode();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (null != obj && obj instanceof Student) {
Student stu = (Student) obj;
name.equals(stu.name);
return true;
}
return false;
}
}
== VS equals()
两个基本类型使用==,比较值是否相等
两个引用类型使用==,比较是否是同一个对象
两个字符串类型使用equals(),是比较内容是否相同
两个其他引用类型使用equals(),如果没有重写equals(),默认比较是否是同一个对象