Java HashMap 可以工作但 containsKey 不能

标签 java hashmap

我试图在 HashMap 中定位一个键。我可以使用“get”打印选定的键,但是当我在 if 语句中使用“containsKey”时,找不到它。

我知道 key 存在于 Map 中,但它一直返回 false。大家有什么想法吗?

我的代码:

public static boolean checkLowerStructuralSupport(Location location) {

    boolean hasSupport = false;

    Location supportingLocation = new Location(location.getX(), location.getY(), location.getZ() - 1);

    System.out.println(_levels.get(supportingLocation.getZ()).getLevelSites2().get(supportingLocation)); //works

    if (_levels.get(supportingLocation.getZ()).getLevelSites2().containsKey(supportingLocation)) {
        hasSupport = true;
    } else {
        hasSupport = false;
    }

    return hasSupport;
}

这是 Location 类的代码:

public class Location {

    protected int _x;
    protected int _y;
    protected int _z;

    public Location(int xAxis, int yAxis, int zAxis) {
        this._x = xAxis;
        this._y = yAxis;
        this._z = zAxis;
    }

    public void equals() {
        //not implemented yet
    }

    public void HashCode() {
        //not implemented yet
    }

    public String toString() {
        String locationString = Integer.toString(_x) + Integer.toString(_y) + Integer.toString(_z);
        return locationString;
    }

    public void setX(int XAxis) {
        this._x = XAxis;
    }

    public int getX() {
        return this._x;
    }

    public void setY(int YAxis) {
        this._y = YAxis;
    }

    public int getY() {
        return this._y;
    }

    public void setZ(int ZAxis) {
        this._z = ZAxis;
    }

    public int getZ() {
        return this._z;
    }

}

最佳答案

您必须确保 Location 类已正确实现其 hashCode()equals(Object) 方法 ( documentation )。也就是说,如果两个 Location 对象实际上相等,它们应该共享一个公共(public)哈希码,并且它们的 equals 方法应该返回 true

关于Java HashMap 可以工作但 containsKey 不能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1104030/

相关文章:

java - JTable - 复选框添加 Action 监听器

java - 如何使用 Gson 将 JSON 转换为 HashMap?

java - 填充对象 HashMap 的 HashMap

java - 服务器不可用时 ActiveMQ java 客户端启动挂起

java - 使用继承的重载方法

java - 通过 Java 进程生成器执行 bash

java - 运行时创建的 varargs 参数列表

java - HashMap 到 Java 类对象

java - 如何将 Guava HashMultmap 转换为 java.util.Map

Java + 列表到 HashMap