【问题标题】:overriding equals and hashCode - java覆盖equals和hashCode - java
【发布时间】:2014-05-29 18:16:26
【问题描述】:

我想在我的 Point 类中重写 equals 和 hashCode 方法。我想在我的列表中使用 Point1 类对象,并且我想检查列表中是否有一个具有相同坐标的点并且它不必是同一个对象。只有字段中的值相同。

这是我的代码,我不知道为什么它不起作用

package prac1;

 import java.util.ArrayList;
 import java.util.List;

    class Point{
        private Integer x;
        private Integer y;

        Point(int x,int y)
        {
            this.x = x;
            this.y = y;
        }

   @Override
    public int hashCode() {
    int hash = 5;
    hash = hash +(this.x != null ? this.x.hashCode() : 0);
    hash = hash/12 + (this.y != null ? this.y.hashCode() : 0); //to have unique hashCode for different objects
    return hash;
}


@Override
public boolean equals(Object other)
    {
        if(this == other) return true; 
        if(other == null) return false; 
        if(getClass() != other.getClass()) return false;

        Point1 test = (Point1)other;
        if(this.x == test.getX() && this.y == test.getY()) 
            return true; 
        return false; 
    }


       int getX(){ return this.x; }
       int getY() {return this.y; }

 }

    public class NewClass{
public static void main(String args[])
{
    List<Point1> lista = new ArrayList<Point1>();
    Point1 t = new Point1(1,1);
    lista.add(t);

    System.out.println(lista.contains(t)); // true
    System.out.println(lista.contains(new Point1(1,1))); // false ?
}
 }

它返回:

   true
   false

谁能告诉我我做错了什么?

【问题讨论】:

  • Point1 是什么?那应该是点吗?另外:重要的是要注意:当我运行您的代码时,假设 Point 和 Point1 应该是同一个类,我得到 'true' 'true' 作为结果

标签: java


【解决方案1】:

如果我将您的 Point 类重命名为 Point1,那么它会在我的机器上生成 true true,因此您的代码可以正常工作。

但是,您的代码中有一个错误。您在 Integer 对象上使用 ==。这仅适用于 -128127 (reference) 之间的整数值,因为它们由 JVM 缓存。但它不适用于更大/更小的值。而是使用.equals

Point1 test = (Point1)other;
if(this.x.equals(test.getX()) && this.y.equals(test.getY())) 
    return true; 
return false; 

这里我省略了if for when this.x == nullthis.y == null,因为构造函数只接受原语,所以目前在您的代码中是不可能的。

【讨论】:

  • @user3131037 不客气。我可以问你为什么在你的哈希函数中使用整数除法吗?这似乎可能会导致您丢失设置位并导致更多哈希冲突。
猜你喜欢
  • 1970-01-01
  • 2011-04-24
  • 2020-06-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-19
相关资源
最近更新 更多