我正在尝试通过我创建的自定义类从 HashMap 获取值。
自定义类:
public class Coordinates {
private int x;
private int y;
public Coordinates(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return this.x;
}
public int getY() {
return this.y;
}
public boolean isSame(Coordinates coords) {
if (coords.getX() == this.x && coords.getY() == this.y) {
return true;
}
return false;
}
public String getAsString() {
return "("+this.x+", "+this.y+")";
}
public Coordinates getCoords() {
return this;
}
}
我有一个名为 coordsJCB 的 HashMap,当我尝试获取 JCButton(自定义 Swing 按钮)时,它说找不到它。
private static HashMap<Coordinates, JCButton> coordsJCB = new HashMap<Coordinates, JCButton>();
coordsJCB.get(coords);
我做了一些调试并注意到
System.out.println(new Coordinates(2, 3).equals(new Coordinates(2, 3)));
打印错误,即使它们是相同的。 我用谷歌搜索并得到了许多关于覆盖 .equals 函数的答案。然而,这对我没有帮助,因为我不想比较 2 个“坐标”实例,我需要通过向 HashMap 传递一个坐标实例来获取值。
非常感谢任何帮助,因为我完全不知道该怎么做。 :/
最佳答案
您需要重写 Cooperatives 类中的 hashCode() 和 equals() 方法。 看看 hashMap 在 Java 中是如何工作的。它将通过调用 equals() 方法来检查对象相等性,该方法的默认实现使用“==”运算符检查引用。 在您的情况下,这将是错误的,因此您无法检索预期的值。
关于java - 将实例与 Java 中的 HashMap 进行比较时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26337169/