Java自定義類型作為HasMap的key的查找


最近常常會用到一些之前看過卻沒有實際去實現的小細節,深有感慨(掌握一門技術絕不是看一遍就夠了,一遍遠遠不夠,遠遠不夠........),

言歸正傳,先直接上代碼

Attributeresult

 1 public class Attributeresult {
 2     String value;
 3     String result;
 4 
 5     public Attributeresult() {
 6 
 7     }
 8 
 9     public Attributeresult(String value, String result) {
10         this.value = value;
11         this.result = result;
12     }
13 
14     @Override
15     public boolean equals(Object o) {
16         if (this == o)
17             return true;
18         if (o == null || getClass() != o.getClass())
19             return false;
20         Attributeresult attributeresult = (Attributeresult) o;
21         if (attributeresult.result == null || attributeresult.value == null)
22             return false;
23         if (value.equals(attributeresult.value) && result.equals(attributeresult.result))
24             return true;
25         return false;
26     }
27 
28     @Override
29     public int hashCode() {
30         return value != null ? value.hashCode() : 0;
31     }
32     public static void main(String[] args) {
33         Map<Attributeresult, Integer> valuelist = new HashMap<Attributeresult, Integer>();
34         valuelist.put(new Attributeresult("mim", "yes"), 20);
35         valuelist.put(new Attributeresult("mim", "no"), 1);
36         valuelist.put(new Attributeresult("xunying", "yes"), 60);
37         valuelist.put(new Attributeresult("xunying", "no"), 2);
38         valuelist.put(new Attributeresult("mini", "no"), 2);
39         if(valuelist.containsKey(new Attributeresult("xunying","yes"))){
40             System.out.println("存在");
41         }else{
42             valuelist.put(new Attributeresult("mini","yes"),30);
43         }
44     }
45 
46 }

運行結果肯定是:存在

這里面Attributeresult類重載了hasCode()方法和equals()方法,所以才能查找存在,如果不重寫,containsKey()返回的必然是false,因為默認情況下是:

HashMap中,查找key的比較順序為:

  1. 計算對象的Hash Code,看在表中是否存在。
  2. 檢查對應Hash Code位置中的對象和當前對象是否相等

第一步就是要用到hashCode()方法,而第二步就是要用到equals()方法。

在沒有進行重載時,在這兩步會默認調用Object類的這兩個方法,而在Object中,Hash Code的計算方法是根據對象的地址進行計算的。

  • 重載hashCode()是為了對同一個key,能得到相同的Hash Code,這樣HashMap就可以定位到我們指定的key上。
  • 重載equals()是為了向HashMap表明當前對象和key上所保存的對象是相等的,這樣我們才真正地獲得了這個key所對應的這個鍵值對。

上面的總結是源於https://segmentfault.com/a/1190000002655085,感謝

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM