我写了一个点类Point
public class Point {
private int x;
private int y;
public Point(){
this.x = 0;
this.y = 0;
}
public Point(int x,int y){
this.x = x;
this.y = y;
}

@Override
public boolean equals(Object p) {
Point point = (Point) p;
if(this.x == point.x&&this.y==point.y)
return true;
else
return false;
}
@Override
public int hashCode() {
// TODO Auto-generated method stub
return super.hashCode();
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
}测试类:TestPoint
public class TestPoint { public static void main(String[] args) {
Point p1 = new Point();
Point p2 = new Point(1,2);
p1.setX(1);
p1.setY(2);
System.out.println(p1.equals(p2));
System.out.println("p1.hashCode = "+p1.hashCode());
System.out.println("p2.hashCode = "+p2.hashCode());
}
}
运行结果:
true
p1.hashCode = 12677476
p2.hashCode = 33263331请问怎么重写hashcode()方法才能使两个相等的点返回相同的hashcode?
谢谢!

解决方案 »

  1.   

    @Override
    public boolean equals(Object p) {
    if (this == p) {
    return true;
    }
    if (p instanceof Point) {
    Point anotherPoint = (Point) p; return anotherPoint.x == this.x && anotherPoint.y == this.y;
    }
    return false;
    } @Override
    public int hashCode() {
    // TODO Auto-generated method stub
    return (this.getClass().getName() + this.x + this.y).hashCode();
    }
      

  2.   


    public int hashCode() { 
    return 11*x+19*y; 

    这样就行了。hashCode可以自已定义的,应当定义为一个良好的散列空间 
    所以一般用素数乘类内成员再求和.(教程上是这么做的.)
      

  3.   


    public int hashCode(){
      return 11*x+19*y;
    }恩,我也刚看过点hashCode的重写例子。确实可行。