我创建了一个 HashMap,它使用自定义类 Location 作为键。 使用 put() 将所有条目插入 HashMap 后,我无法搜索键。
我尝试使用 get()
或 containsKey()
进行搜索,但都没有给出积极的结果。但是,我确信代码中确实存在键,因为我已经使用 HashMap 迭代来打印出键。
下面是代码:
public HashMap<Location, Integer>beenTo = new HashMap<>();
public int uniquePathsIII(int[][] grid) {
for (int i=0; i<grid.length; i++){
for (int j=0; j<grid[0].length; j++){
if (grid[i][j] == 0 || grid[i][j] == 2){
Location newSquare = new Location(i,j);
notBeen.put(newSquare, 1);
}
}
}
Location newSquare = new Location(0,1);
if (notBeen.get(newSquare) != null){
return 10;
}
if (notBeen.isEmpty()){
return -1;
}
}
以下是类(class)位置:
class Location{
int i; // row
int j; // column
public Location(int _i, int _j){
i = _i;
j = _j;
}
public int getI(){
return i;
}
public int getJ(){
return j;
}
public void setI(int _i){
i = _i;
}
public void setJ(int _j){
j = _j;
}
}
在上面的代码中,我想搜索键Location(0,1)
。我已确保 Hashmap notBeen
不为空,并尝试该键确实存在。但我永远无法使用 containsKey()
或 get()
找到它。
最佳答案
如果您希望自定义对象作为 Java 中 HashMap 中的键,则需要实现/覆盖 hashCode
和 equals
方法。
仅供引用:
_variableName
违反了 Java 命名约定 Oracle Java Naming Convention 。这也不是必需的,因为您可以使用以下方法获得相同的结果:
public Location(int i, int j){
this.i = i;
this.j = j;
}
关于java - 使用自定义类作为 HashMap 中的键但无法搜索键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57775196/