Java HashMap可以正常工作,但containsKey却没有

bur*_*gar 14 java hashmap

我试图在HashMap中找到一个键.我可以使用'get'打印所选键,但是当我在if语句中使用'containsKey'时,找不到它.

我知道密钥存在于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;
}
Run Code Online (Sandbox Code Playgroud)

以下是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;
    }

}
Run Code Online (Sandbox Code Playgroud)

Ada*_*ter 23

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

  • 位置课程还有比你展示的更多吗?如图所示,equals和hashCode具有错误的签名(和拼写),因此如果Location继承自超类,那么可能是定义了两者的破坏实现.get/containsKey(至少在JDK1.6中)看起来对我有相同的来源,所以我认为在此期间必须影响你的数据. (3认同)

Mar*_*erg 5

正如这里所描述的那样,你必须覆盖equals(Object)方法.

get(Object)工作的原因是,HashMap将为您的Location类计算Hash并返回hascode指向的Object.

containsKey(Object)计算散列键并获取散列指向的对象.HashMap中的对象将与您放入的Object进行比较.对于这些比较,使用equals方法.当你不覆盖他的equals方法时,当对象引用同一个实例时返回true.

来自HashMap

/** 
 * Check for equality of non-null reference x and possibly-null y. 
 */
static boolean eq(Object x, Object y) {
    return x == y || x.equals(y);
}
Run Code Online (Sandbox Code Playgroud)

来自对象

public boolean equals(Object obj) {
    return (this == obj);
    }
Run Code Online (Sandbox Code Playgroud)

来自等于的javadoc

类Object的equals方法实现了对象上最具辨别力的等价关系; 也就是说,对于任何非空引用值x和y,当且仅当x和y引用同一对象时,此方法才返回true(x == y的值为true).

请注意,通常需要在重写此方法时覆盖hashCode方法,以便维护hashCode方法的常规协定,该方法声明相等对象必须具有相等的哈希代码.

  • 我可能是错的,但我很确定get(...)也会比较密钥(Location)的相等性,并且只使用hash来快速定位它(减少比较次数).如何区分具有相同散列的多个对象(这是完全合法的). (3认同)