首页 > 代码库 > java完美equals方法代码段
java完美equals方法代码段
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); } }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。