java - 使用自定义类作为 HashMap 中的键但无法搜索键

标签 java object hashmap

我创建了一个 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 中的键,则需要实现/覆盖 hashCodeequals 方法。

仅供引用: _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/

相关文章:

java - 错误 yarn.ApplicationMaster : User class threw exception: java. lang.NoClassDefFoundError: scala/Function0$class

java - Android Java 检索 JSON 值并将其作为对象存储在列表中

java - 如何用Java编写HashMap的put方法?

python - Python 字典是哈希表的一个例子吗?

c++ - 我可以将对象插入 tr1 unordered_map 吗

java - 简单的定时器,时间间隔怎么讲?

java - 在选择树的复选框时显示/隐藏组件

java - 有没有办法在方法参数中将 Java 代码片段作为 Groovy Closure 传递?

javascript - 使用 ES6 过滤带有数组的对象

javascript - 为什么我会收到此错误?未捕获的类型错误: state.removeFlag不是函数