zl程序教程

您现在的位置是:首页 >  后端

当前栏目

java完美equals方法代码段

JAVA方法 完美 equals 代码段
2023-09-11 14:21:00 时间
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);
     }
}