在HashMap中使用自定义类作为键,但无法搜索键 [英] Using a customed class as keys to in HashMap but not able to search the keys
问题描述
我创建了一个使用自定义类Location作为键的HashMap.
使用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 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命名约定.这也是不必要的,因为您可以使用以下方法获得相同的结果:
public Location(int i, int j){
this.i = i;
this.j = j;
}
I created a HashMap that uses a customed class Location as keys.
After inserting all the entries into the HashMap using put()
, I am not able to search the keys.
I have tried to use get()
or containsKey()
to search, but neither give me positive results. However, I am sure that the keys do exists in the code because I have used HashMap iteration to print out the keys.
Below is the code:
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;
}
}
Below is the class Location:
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;
}
}
In the above code, I wanted to search for the key Location(0,1)
. I have made sure that the Hashmap notBeen
is not empty, and tried that the key does exist. But I am never able to find it using containsKey()
nor get()
.
You need to implement/override hashCode
and equals
methods if you want a custom Object to work as a key in a HashMap in Java.
FYI:
_variableName
goes against Java naming conventions Oracle Java Naming Convention. It is also not necessary as you can get the same result using:
public Location(int i, int j){
this.i = i;
this.j = j;
}
这篇关于在HashMap中使用自定义类作为键,但无法搜索键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!