写一个“完美”的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-09-28微服务架构中API版本控制的实践
- 2024-09-28AI给的和自己写的Python代码,都无法改变输入框的内容,替换也不行
- 2024-09-27Sentinel配置限流资料:新手入门教程
- 2024-09-27Sentinel配置限流资料详解
- 2024-09-27Sentinel限流资料:新手入门教程
- 2024-09-26Sentinel限流资料入门详解
- 2024-09-26Springboot框架资料:初学者入门教程
- 2024-09-26Springboot框架资料详解:新手入门教程
- 2024-09-26Springboot企业级开发资料:新手入门指南
- 2024-09-26SpringBoot企业级开发资料新手指南