您的位置:首页 > 其它

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

2017-11-21 01:10 295 查看
显示的参数命名为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.Arrays
static Boolean equlas(type[] a, type[] b)
/*如果两个数组长度相同,并且在对应的位置上数据元素也均相同,将返回true。*/

//java.util.Objects
static boolean equals(Object a, Object b)
/*如果a和b都为null,返回true;如果只有其中之一为null,则返回false;否则返回a.equals(b)*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐