equals方法的编写建议

  • 1.显示参数命名为 otherObject ,稍后需要将其转换成另一个叫做 other 的变量。
  • 2.检测 thisotherObject 是否引用同一个对象:
//这条语句只是一个优化。计算这个等式比一个一个地比较类中的域所付出的代价要小的多。
if (this == otherObject) return true;
  • 3.检测otherObject是否为null,如果为null,则返回false
  • 4.比较thisotherObject 是否属于同一个类:
    如果equals的语义在每个子类中有所改变,就用getClass检测; 如果所有子类都有统一的语义,就用instanceof检测:
//getClass
if(getClass != otherObject.getClass())
	return false;
//instanceof
if(!(otherObject instanceof ClassName))
	return false;
  • 5.将otherObject转换成相应的类的类型变量:ClassName other = (ClassName)otherObject;
  • 6.现在开始对所有需要比较的域进行比较了。使用==比较基本类型域,使用equals比较对象域。如果所有的域都匹配,就返回ture,否则返回false
return field1 == other.field1
	&& Objects.equals(field2,other.field2)
	&&···

如果在子类中重新定义equals,就要在其中包含调用super.equals(other);

posted @ 2018-04-09 16:24  guoyangde  阅读(210)  评论(0编辑  收藏  举报