標籤:
最近常常會用到一些之前看過卻沒有實際去實現的小細節,深有感慨(掌握一門技術絕不是看一遍就夠了,一遍遠遠不夠,遠遠不夠........),
言歸正傳,先直接上代碼
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的比較順序為:
- 計算對象的
Hash Code,看在表中是否存在。
- 檢查對應
Hash Code位置中的對象和當前對象是否相等
第一步就是要用到hashCode()方法,而第二步就是要用到equals()方法。
在沒有進行重載時,在這兩步會預設調用Object類的這兩個方法,而在Object中,Hash Code的計算方法是根據對象的地址進行計算的。
- 重載
hashCode()是為了對同一個key,能得到相同的Hash Code,這樣HashMap就可以定位到我們指定的key上。
- 重載
equals()是為了向HashMap表明當前對象和key上所儲存的對象是相等的,這樣我們才真正地獲得了這個key所對應的這個索引值對。
上面的總結是源於1190000002655085,感謝
Java自訂類型作為HasMap的key的尋找