有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java hashcode和equals重写不起作用,怎么了

我正在使用coder pad来做这件事,结果似乎显示,即使在重写hashCode和equals之后,我也会重复。谢谢你的帮助

   public static class Point{//just a class
       int x, y;
       Point(int x, int y){
         this.x = x;
         this.y = y;
       }
     // @Override
       public int hashCode(){//17 and 31 from effective java
            int result = 17;
            result = 31 * result + x;
            result = 31 * result + y;
           return result;
       }
    //  @Override
       public boolean equals(Point p){
          return p.x == x && p.y == y;
       }
    }
    public static void main(String[] args) {//main func
    Set<Point> res = new HashSet<>();
    res.add(new Point(100, 0));
    res.add(new Point(100, 0));
    for (Point a: res){   
      System.out.println(a.x + " " + a.y);
  }

共 (1) 个答案

  1. # 1 楼答案

    你没有重写equals,你重载equals,这是行不通的

    你的equals方法必须接受一个对象参数,然后根据需要进行强制转换。你必须写下这样的东西

    public boolean equals(Object o) {
      if (o instanceof Point) {
        Point p = (Point) o;
        return x==p.x && y==p.y;
      }
      return false;
    }