[童虎退壳系列]判等与哈希值的覆写_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > [童虎退壳系列]判等与哈希值的覆写

[童虎退壳系列]判等与哈希值的覆写

 2011/10/13 8:12:37  marshan  http://marshan.iteye.com  我要评论(0)
  • 摘要:publicfinalclassEqualsHashCode{finalintx;finalinty;publicEqualsHashCode(intx,inty){this.x=x;this.y=y;}@Overridepublicbooleanequals(Objectobj){if(this==obj)returntrue;if(objinstanceofEqualsHashCode){System.out.println("instanceoftestsuccessfully.")
  • 标签:

public final class EqualsHashCode {
	final int x;
	final int y;

	public EqualsHashCode(int x, int y) {
		this.x = x;
		this.y = y;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;

		if (obj instanceof EqualsHashCode) {
			System.out.println("instanceof test successfully.");
			EqualsHashCode other = (EqualsHashCode) obj;
			return this.x == other.x && this.y == other.y;
		} else if (obj == null) {
			System.out.println("instanceof test a null object is not raised an exception.");
			return false;
		}
		return true;
	}

	@Override
	public int hashCode() {
		return x ^ y;
	}

	@Override
	public String toString() {
		return "x=" + x + "y=" + y;
	}

	public static void main(String[] args) {
		EqualsHashCode thiz1 = new EqualsHashCode(1, 2);
		EqualsHashCode thiz2 = new EqualsHashCode(2, 1);
		EqualsHashCode thiz3 = new EqualsHashCode(2, 1);
		thiz1.equals(null);
		System.out.println(thiz1.hashCode());
		System.out.println(thiz2.hashCode());
		System.out.println(thiz1.equals(thiz2));
		System.out.println(thiz3.equals(thiz2));
	}
}
?
  • 相关文章
发表评论
用户名: 匿名