簡體   English   中英

哈希圖 <Node, Integer> 即使hashcode()相同,get也會返回null

[英]HashMap<Node, Integer> get returns null even when hashcode() is the same

我有一個自定義類Node:

public static class Node{

    int _id;
    // adjacent node and its cost
    HashMap<Node, Integer> _adjList = new HashMap<>();

    public Node(int id){
        _id = id;
    }

    public boolean equals(Node n) {
        if (n == null)
            return false;
        return _id == n._id;
    }

    public int hashCode(){
            return _id;
    }

    public String toString(){
        return "("+_id+")";
    }

}//Node

我將其用作HashMap<Node, Integer> costs ,對於給定節點,到達與其關聯的節點會產生成本。 在程序的后面,我將用值填充costs

{(1)=0, (2)=24, (3)=3, (4)=15}

然后,在代碼的后面,當我查詢costs時:

 for (int i = 0; i <= g.nNodes; ++i){
            Node tempNode = new Node(i);
            Integer cost = currentPathCosts.get(tempNode);
            System.out.println("cost:"+cost);
        }

我懂了

null
null
null

作為輸出。 怎么了? 具有相同_id的節點的hashcode()應該相同。我是否缺少某些內容?


更新:

我錯過了Node other =(Node)n; 在equals()方法中。 覆蓋對我有用的hashcode()和equals()的方法:

        @Override
        public boolean equals(Object n) {
            if (n == null)
                return false;
            Node other = (Node)n;
            return _id == other._id;
        }
        @Override
        public int hashCode(){
                return _id;
        }

就像在要覆蓋方法時應始終執行的操作一樣,在equals()方法上添加@Override批注,編譯器會告訴您問題出在哪里。 (對hashCode進行同樣的操作)。

您沒有覆蓋Object.equals() 您正在定義一個不同的重載equals()方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM