equals方法用于判断当前对象this与另一个对象obj是否相等。
必须遵守的规则:
• 对称性:如果x.equals(y)返回是“true”,那么y.equals(x)也应该返回是“true”。
• 反射性:x.equals(x)必须返回是“true”。
• 类推性:如果x.equals(y)返回是“true”,而且y.equals(z)返回是“true”,那么z.equals(x)也应该返回是“true”。
• 还有一致性:如果x.equals(y)返回是“true”,只要x和y内容一直不变,不管你重复x.equals(y)多少次,返回都是“true”。
• 任何情况下,x.equals(null),永远返回是“false”;x.equals(和x不同类型的对象)永远返回是“false”。
• 反射性:x.equals(x)必须返回是“true”。
• 类推性:如果x.equals(y)返回是“true”,而且y.equals(z)返回是“true”,那么z.equals(x)也应该返回是“true”。
• 还有一致性:如果x.equals(y)返回是“true”,只要x和y内容一直不变,不管你重复x.equals(y)多少次,返回都是“true”。
• 任何情况下,x.equals(null),永远返回是“false”;x.equals(和x不同类型的对象)永远返回是“false”。
流程:
1.是否是同一个引用?是则返回true;
2.obj是否为空指针?是则返回false;
3.this与obj是否是同一个class的instance?否则返回false;
4.逐一比较this与obj的成员是否相等,首先判断二者的成员是否为空,如果只有一个为空或者都不为空但不想等,则返回false;
5.返回true。
下面是一个例子:
public class Action
{
private String deviceMacAddr;
private String attribute;
private String operation;
private String value;
{
private String deviceMacAddr;
private String attribute;
private String operation;
private String value;
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Action other = (Action) obj;
if (attribute == null)
{
if (other.attribute != null)
return false;
}
else if (!attribute.equals(other.attribute))
return false;
if (deviceMacAddr == null)
{
if (other.deviceMacAddr != null)
return false;
}
else if (!deviceMacAddr.equals(other.deviceMacAddr))
return false;
if (operation == null)
{
if (other.operation != null)
return false;
}
else if (!operation.equals(other.operation))
return false;
if (value == null)
{
if (other.value != null)
return false;
}
else if (!value.equals(other.value))
return false;
return true;
}
}
{
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Action other = (Action) obj;
if (attribute == null)
{
if (other.attribute != null)
return false;
}
else if (!attribute.equals(other.attribute))
return false;
if (deviceMacAddr == null)
{
if (other.deviceMacAddr != null)
return false;
}
else if (!deviceMacAddr.equals(other.deviceMacAddr))
return false;
if (operation == null)
{
if (other.operation != null)
return false;
}
else if (!operation.equals(other.operation))
return false;
if (value == null)
{
if (other.value != null)
return false;
}
else if (!value.equals(other.value))
return false;
return true;
}
}