foxhuntd 2011-04-05 11:25
浏览 197
已采纳

这个测试,为什么总是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]

  • 写回答

3条回答 默认 最新

  • iteye_12540 2011-04-05 11:44
    关注

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥15 树莓派5怎么用camera module 3啊
  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事: