重写equals方法的建议

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Never_Blue/article/details/85246435

在Objdect类中,equals方法用于检测两个对象是否具有相同的引用。因此equals方法也常常被各种类重写,下面给出一些重写equals方法的建议:

1)将参数命名为otherObject。

2)比较this和otherObject是否引用同一个对象:

if(this == otherObject)    return true;

3)比较otherObject是否为null,如果为null,返回false:

if(otherObject == null)    return false;

4)比较thi和otherObject是否属于同一个类。

   如果equals方法在每个子类中有所改变,就使用getClass检测:

if(getClass != otherObject.getClass())    return false;

   如果equals方法在每个子类中都是统一的语义,就使用instanceof检测:

if(!(otherObject instanceof ClassName))    return false;

5)将otherObject转换为对应的类类型量,针对需求选取特定的域进行比较。使用==比较基本类型域,使用equals比较对象域。如果所有域都匹配,则返回true,否则返回false。如果在子类中重新定义equals,要在其中包含super.equals(otherObject)。

ClassName other = (ClassName)otherObject;
super.equals(other);
return field1 == other.field1 && Objects.equals(field2, other.field2) && ...;

猜你喜欢

转载自blog.csdn.net/Never_Blue/article/details/85246435