Objects中的equals方法用于检测一个对象是否等于另外一个对象。判断两个对象是否具有相同的引用
源码如下
public boolean equals(Object obj) {
return (this == obj);
}
可以看到,equals方法是直接判断this和obj本身的值是否相等,即用来判断调用equals的对象和形参obj所引用的对象是否是同一对象,所谓同一对象就是指内存中同一块存储单元,如果this和obj指向的hi同一块内存对象,则返回true,如果this和obj指向的不是同一块内存,则返回false,注意:即便是内容完全相等的两块不同的内存对象,也返回false。
如果是同一块内存,则object中的equals方法返回true,如果是不同的内存,则返回false
官方文档中的说明:
It is reflexive: for any non-null reference value x, x.equals(x) should return true.
自反性,对于非空引用x,x.equals(x) == true;
It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
对称性,y.equals(x)=ture时,x.equals(y)==true;
It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.
传递性,f x.equals(y) = true , y.equals(z) = true —> x.equals(z) == true.
It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified.
一致性,如果x和y引用的对象都没有发生变化,反复调用x.euqlas(y)返回同样结果。
For any non-null reference value x, x.equals(null) should return false.
对于任何非空引用x , x.equals(null)=false
在很多情况下,这种判断没什么意义。常常需要我们重写。
public boolean equals(Object otherObject)
{
// a quick test to see if the objects are identical
if (this == otherObject) return true;
// must return false if the explicit parameter is null
if (otherObject == null) return false;
// if the classes don't match, they can't be equal
if (getClass() != otherObject.getClass()) return false;
// now we know otherObject is a non-null Employee
Employee other = (Employee) otherObject;
// test whether the fields have identical values
return Objects.equals(name, other.name) && salary == other.salary && Objects.equals(hireDay, other.hireDay);
}
如果所有的子类有统一的语义,就使用Instanceof检测:
if(!(otherObject instanceof ClassName)) return false;
在子类中定义 equals
方法时,首先调用超类的equals
,如果检测失败,对象就不能相等。如果超类中的域都相等,就需要比较子类中的实例域。
public boolean equals(Object otherObject)
{
if (!super.equals(otherObject)) return false;
Manager other = (Manager) otherObject;
// super.equals checked that this and other belong to the same class
return bonus == other.bonus;
}
equals和hashcode的关系
1、如果两个对象equals相等,那么这两个对象的HashCode一定也相同
2、如果两个对象的HashCode相同,不代表两个对象就相同,只能说明这两个对象在散列存储结构中,存放于同一个位置!