这个测试,为什么总是false

[code="java"]//TPoint.java
/*
This is just a trivial "struct" type class --
it simply holds an int x/y point for use by Tetris,
and supports equals() and toString().
We'll allow public access to x/y, so this
is not an object really.
*/
public class TPoint {
public int x;
public int y;

// Creates a TPoint based in int x,y
public TPoint(int x, int y) {
    // questionable style but convenient --
    // params with same name as ivars

    this.x = x;
    this.y = y;
}

// Creates a TPoint, copied from an existing TPoint
public TPoint(TPoint point) {
    this.x = point.x;
    this.y = point.y;
}

// Standard equals() override
public boolean equals(Object other) {
    // standard two checks for equals()
    if (this == other) return true;
    if (!(other instanceof TPoint)) return false;

    // check if other point same as us
    TPoint pt = (TPoint)other;
    return(x==pt.x && y==pt.y);
}

// Standard toString() override, produce
// human-readable String from object
public String toString() {
    return "(" + x + "," + y + ")";
}

}
[/code]

[code="java"]
import java.util.HashSet;

public class test {

/**
 * @param args
 */
public static void main(String[] args) {
    TPoint a =new TPoint(0,1);
    TPoint b =new TPoint(0,1);
    HashSet<TPoint> setA = new HashSet<TPoint>();
    HashSet<TPoint> setB = new HashSet<TPoint>();
    setA.add(a);
    setB.add(b);
    boolean res = setA.equals(setB);
    System.out.println(res);


}

}
[/code]

因为你没有重写hashCode。既然是HashSet,那么你不重写这个,Hash值都不一样,当然对不上。

你只重写了TPoint的equals方法,但是你调用的是Hashset的equals方法,Hashset的equals方法你并没有重写哦

请重写TPoint的hashCode方法。上面的不要误人子弟。
默认从Object继承来的hashCode是基于对象的ID实现的。
如果你重载了equals,比如说是基于对象的内容实现的,而保留hashCode的实现不变,那么很可能某两个对象明明是“相等”,而hashCode却不一样。
这样,当你用其中的一个作为键保存到hashMap、hasoTable或hashSet中,再以“相等的”找另一个作为键值去查找他们的时候,则根本找不到。