繁体   English   中英

使用自定义类作为 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 中的键,则需要实现/覆盖hashCodeequals方法。

仅供参考: _variableName违反 Java 命名约定Oracle Java 命名约定 也没有必要,因为您可以使用以下方法获得相同的结果:

public Location(int i, int j){
  this.i = i;
  this.j = j;
}

为了避免内存泄漏,map 的 key 必须是不可变对象,并提高搜索 key 的速度,key 对象有 equals() 和 hashcode() 方法是一种很好的做法(先使用 hashcode 判断 equals 然后使用 equals() 方法)。在你的代码最好使位置不可变(不支持 setter 方法)。

public class Location {
    private final int i;
    private final int j;

    public Location(int x, int y) {
        this.i = x;
        this.j = y;
    }

    public int getI() {
        return i;
    }

    public int getJ() {
        return j;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (!(o instanceof Location)) {
            return false;
        }
        Location point = (Location) o;
        return i == point.i &&
            j == point.j;
    }

    @Override
    public int hashCode() {
        return Objects.hash(i, j);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM