我试图在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)
正如这里所描述的那样,你必须覆盖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方法的常规协定,该方法声明相等对象必须具有相等的哈希代码.
| 归档时间: |
|
| 查看次数: |
38914 次 |
| 最近记录: |