写一个“完美”的Java的equals方法
2021/7/18 14:35:46
本文主要是介绍写一个“完美”的Java的equals方法,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
写一个“完美”的Java的equals方法
原文
摘自Core Java(Volume I--Fundamentals 9th Edition):
- Name the explicit parameter otherObject—later, you will need to cast it to another variable that you should call other.
- Test whether this happens to be identical to otherObject:
if (this == otherObject) return true;
This statement is just an optimization. In practice, this is a common case. It is
much cheaper to check for identity than to compare the fields.- Test whether otherObject is null and return false if it is. This test is
required.
if (otherObject == null) return false;
- Compare the classes of this and otherObject. If the semantics of equals
can change in subclasses, use the getClass test:
if (getClass() != otherObject.getClass()) return false;
If the same semantics holds for all subclasses, you can use an instanceof test:
if (!(otherObject instanceof ClassName)) return false;
- Cast otherObject to a variable of your class type:
ClassName other = (ClassName) otherObject
- Now compare the fields, as required by your notion of equality. Use == for
primitive type fields, Objects.equals for object fields. Return true if all fields
match, false otherwise.
return field1 == other.field1 && Objects.equals(field2, other.field2) && . . .;
If you redefine equals in a subclass, include a call tosuper.equals(other)
.
笔记
- 直接比较是否是同一个引用;
- 判断需要去比较的对象是否为null;
- 比较:
equals的语义在子类有所变化,使用getClass;
子类和父类的equals语义一致,使用instanceof; - 类型转换;
- 根据要求进一步比较域。
关于getClass和instanceof的理解:
getClass的规则是:采用==来进行检查是否相等的,是严格的判断,不会存在继承方面的考虑,也就是说只判断该继承层次上是否equals,进一步说子类的equals语义变化了。
instanceof的规则是:你属于该类或者该类的子类吗?考虑了继承,继承层次上equals语义一致;
参考:http://blog.csdn.net/hzw19920329/article/details/51095413
这篇关于写一个“完美”的Java的equals方法的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-15JavaMailSender是什么,怎么使用?-icode9专业技术文章分享
- 2024-11-15JWT 用户校验学习:从入门到实践
- 2024-11-15Nest学习:新手入门全面指南
- 2024-11-15RestfulAPI学习:新手入门指南
- 2024-11-15Server Component学习:入门教程与实践指南
- 2024-11-15动态路由入门:新手必读指南
- 2024-11-15JWT 用户校验入门:轻松掌握JWT认证基础
- 2024-11-15Nest后端开发入门指南
- 2024-11-15Nest后端开发入门教程
- 2024-11-15RestfulAPI入门:新手快速上手指南