默认情况下,当我们没有为自定义类提供实现时,Object类的equals方法会被调用。Object类的equals方法使用引用比较对象。
例如,a.equals(a); 总是返回true。
如果我们要提供自己的实现,则需要对对象的相等性采取某些步骤。
Reflexive: a.equals(a) always returns true;
Symmetric: if a.equals(b) is true then b.equals(a) should also be true.
Transitive: If a.equals(b), b.equals(c) then a.equals(c) should be true/false according to previous 2 result.
Consistent: a.equals(b) should be the same result without modifying the values of a and b.
注意:默认的equals方法检查引用,即==运算符。
注意:对于任何非空引用值a,a.equals(null)应返回false。
public class ObjectEqualExample{
public static void main(String []args){
Employee e1 = new Employee(1, "A");
Employee e2 = new Employee(1, "A");
System.out.println(e1.equals(e1));
System.out.println(e1.equals(e2));
}
}
class Employee {
private int id;
private String name;
@Override
public String toString() {
return "{id ="+id+", name = "+name+"} ";
}
@Override
public boolean equals(Object o) {
if(this == o) return true;
if(o == null || o.getClass() != this.getClass()) return false;
Employee employee = (Employee)o;
if(employee.id == this.id && employee.name.equals(this.name)) {
return true;
} else return false;
}
public int hashCode() {
return id;
}
public Employee(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
}