Java HashMap get works but containsKey does not(Java HashMap get 有效,但 containsKey 无效)
问题描述
我正在尝试在 HashMap 中找到一个键.我可以使用 'get' 打印选定的键,但是当我在 if 语句中使用 'containsKey' 时,找不到它.
I am trying to locate a key in a HashMap. I can print the selected key by using 'get' but when I use 'containsKey' in an if statement, it is not found.
我知道密钥存在于地图中,但它一直返回错误.有什么想法吗?
I KNOW the key is present in the Map but it keeps returning false. Any ideas people?
我的代码:
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 类的代码:
Here is the code for the Location class:
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(对象)
方法(文档).也就是说,如果两个 Location
对象实际上是相等的,它们应该共享一个公共哈希码,并且它们的 equals
方法应该返回 true
.
You must ensure that the Location
class has properly implemented its hashCode()
and equals(Object)
methods (documentation). That is, if two Location
objects are effectively equal, they should share a common hash code and their equals
method should return true
.
这篇关于Java HashMap get 有效,但 containsKey 无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java HashMap get 有效,但 containsKey 无效
基础教程推荐
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 降序排序:Java Map 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01