您的位置:首页 > 编程语言 > Java开发

java完美equals方法代码段

2015-12-23 18:24 405 查看
public boolean equals(Object otherObject) {
if(this == otherObject) {    // 检測this与otherObject是否引用同一个对象
return true;
}

if(null == otherObject ) {   // 检測otherObject是否为空
return false;
}

if(!(getClass() == otherObject.getClass())){  // 比較this与oherObject是否属于同一个类,假设equal的语义在每一个子类中有所改变,就用此推断
System.out.println("-----------------getClass----------------");
return false;
}

if( ! (otherObject instanceof Apple)) {  // 假设语义同样就用instanceof推断,推断继承时也用到
System.out.println("------------instanceof--------------------");
return false;
}

Apple other = (Apple) otherObject;  // 转换为对应类型。对所需域进行推断

return name.equals(other.name)&& color.equals(other.color);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: