`

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

    博客分类:
  • java
阅读更多

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));
	}
}
 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics