基础巩固--编写一个完美的equals方法

来源:互联网 发布:机械革命 知乎 编辑:程序博客网 时间:2024/05/21 06:47

显示的参数命名为otherObject。
1,检测this与otherObject是否引用同一个对象:

if(this == otherObject) return true;

2,检测otherObject是否为null:

if(otherObject == null) return false;

3,比较this与otherObject是否属于一个类。
如果equals的语义在每个子类中有所改变,就使用getClass检测:

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

如果所有的子类都拥有统一的语义,就使用instanceof检测:

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

4,将otherObject转换为相应的类类型变量:

ClassName other = (ClassName) otherObject;

5,对所有需要比较的域进行比较。使用==比较基本数据类型,使用Objects.equals比较对象域:

return this.field1 == other.field1 && Objects.equals(this.field2, other.field2) && ...;
//java.util.Arraysstatic Boolean equlas(type[] a, type[] b)/*如果两个数组长度相同,并且在对应的位置上数据元素也均相同,将返回true。*///java.util.Objectsstatic boolean equals(Object a, Object b)/*如果a和b都为null,返回true;如果只有其中之一为null,则返回false;否则返回a.equals(b)*/
原创粉丝点击