equals 用法建议
1.显式参数命名为otherObject,稍后需要将它转换成另一个叫做other的变量。
2.检测this与otherObject是否引用同一个对象
if (this == otherObject) return true;
这条语句只是一个优化。实际上,这是一种经常采用的形式。因为计算这个等式要比一个一个地比较类中的域所付出的代价小得多。
3.检测otherObject是否为null,如果为null,返回false。
if (otherObject == null) return false;
4.比较this与otherObject是否属于同一个类。如果equals的语言在每个子类中有所改变,就使用getClass检测:
if (getClass() != otherObject.getClass()) return false;
如果所有的子类都拥有统一的语义,就使用instanceof检测:
if (!(otherObject instanceof ClassName)) return false;
5.将otherObject转换为相应的类类型变量:
ClassName other = (ClassName)otherObject
6.现在开始对所有需要比较的域进行比较了。使用==比较基本类型域,使用equals比较对象域。如果所有的域都匹配,就返回true;否则返回false.
return field1 == other.field1 && field2.equals(other.field2)&&...;
如果在子类中重新定义equals,就要在其中包含调用super.equals(other);
若没有覆盖Object类的equals方法,可以使用@Override对覆盖超类方法进行标记:
@Override public boolean equals(Object other)
代码示例:
package com.test.xqh;
public class EqualsTest {
public static void main(String[] args) {
Person p = new Person("张三", "110");
Person p1 = new Person("李四", "110");
Person p2 = new Person("张三", "110");
System.out.println(p.equals(p2)); // true
System.out.println(p.equals(p1)); // false
}
}
class Person {
private String name;
private String ID;
Person(String name, String ID) {
this.name = name;
this.ID = ID;
}
Person() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getID() {
return ID;
}
public void setID(String iD) {
ID = iD;
}
public boolean equals(Object otherObject) {
if (this == otherObject)
return true;
if (otherObject == null)
return false;
if (getClass() != otherObject.getClass())
return false;
if (!(otherObject instanceof Person))
return false;
Person p = (Person) otherObject;
return name.equals(p.name) && ID.equals(p.ID);
//return name == p.name && ID == p.ID;
}
}