Java自訂類型作為HasMap的key的尋找

來源:互聯網
上載者:User

標籤:

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

言歸正傳,先直接上代碼

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     @Override15     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     @Override29     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所對應的這個索引值對。

上面的總結是源於1190000002655085,感謝

 

Java自訂類型作為HasMap的key的尋找

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.