1 简介
Object 类中的 equals
方法用于检测一个对象是否等于另外一个对象,也就是说判断这两个对象是否具有相同的引用,然而, 对于大多数类来说,这种判断并没有什么意义,大多数情况下,我们都需要检测两个对象状态的相等性,如果这两个对象的状态相等,就认为这两个对象是相等的。
所以,jdk/src/Object.java中可以找到`equals``的定义如下:
public boolean equals(Object obj) {
return (this == obj);
}
在 j2se7 中有如下说明:
public boolean equals(Object obj)
(Indicates whether some other object is “equal to” this one. )The equals method implements an equivalence relation on non-null object references:
- It is reflexive: for any non-null reference value x, x.equals(x) should return 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.- 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.- 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.- For any non-null reference value x, x.equals(null) should return false.
The equals method for class Object implements the most discriminating
possible equivalence relation on objects; that is, for any non-null
reference values x and y, this method returns true if and only if x
and y refer to the same object (x == y has the value true).Note that it is generally necessary to override the hashCode method
whenever this method is overridden, so as to maintain the general
contract for the hashCode method, which states that equal objects must
have equal hash codes.Parameters: obj - the reference object with which to compare.
Returns: true if this object is the same as the obj argument; false otherwise.
2 Java语言规范对于equals方法的要求:
- 自反性:对于任何非空引用x,
x.equals(x)
应该返回 true - 对称性:对于任何引用x和y,当且仅当
y.equals(x)
返回 true,x.equals(y)
也应该返回 true - 传递性:对于任何引用x和y和z,当且仅当
x.equals(y)
返回 true,y.equals(z)
返回 true,x.equals(z)
也应该返回 true - 一致性:如果x和y的引用的对象没有发生变化,反复调用
x.equals(y)
应该返回相同的结果 - 对于任何非空引用x,
x.equals(null)
应该返回 false
3 编写equals方法:
3.1 通式
@Override
public boolean equals(Object obj) {
/* 1、检测 this 和 obj 是否引用同一个对象 */
if (this == obj) {
return true;
}
/* 2、检测 obj 是否为 null,如果为 null,返回 false */
if (obj == null) {
return false;
}
/* 3、检测 obj 和 this 是否属于同一个类 */
// 如果所以子类都统一,就用 instanceof
boolean b = obj instanceof ClassName;
// 否则
boolean b = getClass() == obj.getClass();
/* 4、转型 */
ClassName other = (ClassName) obj;
/* 5、比较所有域 */
return field == other.field;
}
3.2 简单的例子
public class Person {
String name;
int age;
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
boolean b = obj instanceof Person;
if (b) {
Person p = (Person)obj;
return (this.age == p.age && this.name.equals(p.name);
} else {
return false;
}
}
}
参考:
1、Java编程思想 - Bruce Eckel
2、Java核心技术(卷1) - Cay S.Horstmann