我想重写 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
谁能告诉我我做错了什么?
最佳答案
如果我将您的 Point
类重命名为 Point1
那么它会在我的机器上生成 true
true
,所以您的代码有效。
但是您的代码中有一个错误。您正在 Integer
对象上使用 ==
。这仅适用于 -128
和 127
( reference ) 之间的整数值,因为这些值由 JVM 缓存。但它不适用于较大/较小的值。而是使用 .equals
Point1 test = (Point1)other;
if(this.x.equals(test.getX()) && this.y.equals(test.getY()))
return true;
return false;
这里我遗漏了一个 if
来表示 this.x == null
或 this.y == null
这在你的代码中是不可能的由于构造函数仅接受基元,因此目前的代码。
关于java - 重写 equals 和 hashCode - java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23930506/