首页 > 代码库 > 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);
     }
}