java完美equals方法代码段

时间:2014-06-08 04:00:26   收藏:0   阅读:299
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);
     }
}

java完美equals方法代码段,布布扣,bubuko.com

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!