集合架構之HashSet如何保證元素唯一性的原理,架構hashset
一: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 @Override14 public boolean equals(Object obj) {15 if (this == obj)// 調用的對象和傳入的對象是同一個對象16 return true;// 直接返回true17 if (obj == null)// 傳入的對象為null18 return false;// 返回false19 if (getClass() != obj.getClass())// 判斷兩個對象的位元組碼檔案是否是同一個對象20 return false;// 如果不是返回false21 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 }