一:HashSet原理
我們使用Set集合都是需要去掉重復元素的, 如果在存儲的時候逐個equals()比較, 效率較低,哈希算法提高了去重復的效率, 降低了使用equals()方法的次數
當HashSet調用add()方法存儲對象的時候, 先調用對象的hashCode()方法得到一個哈希值, 然后在集合中查找是否有哈希值相同的對象
如果沒有哈希值相同的對象就直接存入集合
如果有哈希值相同的對象, 就和哈希值相同的對象逐個進行equals()比較,比較結果為false就存入, true則不存
二:將自定義類的對象存入HashSet去重復
類中必須重寫hashCode()和equals()方法
hashCode(): 屬性相同的對象返回值必須相同, 屬性不同的返回值盡量不同(提高效率)
equals(): 屬性相同返回true, 屬性不同返回false,返回false的時候存儲(注意存儲自定義對象去重時必須同時重寫hashCode()和equals()方法,因為equals方法是按照對象地址值比較的)
三:ecplise自動重寫hashCode()和equals()方法解讀
1 /* 2 * 為什么是31? 1:31是一個質數 2:31個數既不大也不小 3:31這個數好算,2的五次方減一 3 */ 4 @Override 5 public int hashCode() { 6 final int prime = 31; 7 int result = 1; 8 result = prime * result + ((name == null) ? 0 : name.hashCode()); 9 result = prime * result + ((sex == null) ? 0 : sex.hashCode()); 10 return result; 11 } 12 13 @Override 14 public boolean equals(Object obj) { 15 if (this == obj)// 調用的對象和傳入的對象是同一個對象 16 return true;// 直接返回true 17 if (obj == null)// 傳入的對象為null 18 return false;// 返回false 19 if (getClass() != obj.getClass())// 判斷兩個對象的字節碼文件是否是同一個對象 20 return false;// 如果不是返回false 21 Person other = (Person) obj;// 向下轉型 22 if (name == null) { 23 if (other.name != null) 24 return false; 25 } else if (!name.equals(other.name)) 26 return false; 27 if (sex == null) { 28 if (other.sex != null) 29 return false; 30 } else if (!sex.equals(other.sex)) 31 return false; 32 return true; 33 }