一、hashCode()的作用
hashCode()是用來計算雜湊值的,在對資料進行儲存的時候,假如有成千上萬個資料,每當存入一個資料,就需要比較多次,這樣效率就很低,採用雜湊值演算法得到雜湊值後,根據雜湊值劃分為不同的地區,這樣就能大大減少比較次數,提高效率。:
二、ArrayList_HashSet的比較及Hashcode分析
在自訂類中類型添加到HashSet中通常要要重寫hashCode方法和equlas方法,依此來判斷元素是否重複。在進行判斷元素是否相同時,先調用hashCode方法,如果雜湊值一樣,再調用equals方法繼續比較判斷。如果雜湊值不同,則不再調用equals方法進行判斷。
注意:雜湊值相同,兩個對象不一定相等,兩個對象相等,這兩個對象的雜湊值一定相等。
記憶體泄露:對象不需要再使用了,卻沒有引用指向它,未進行回收。
見代碼:
public class ReflectPoint{ public int x; public int y;public ReflectPoint(int x, int y){super();this.x = x;this.y = y;}public String toString(){return this.x+" "+this.y;}@Overridepublic int hashCode() {final int prime = 31;int result = 1;result = prime * result + x;result = prime * result + y;return result;}@Overridepublic boolean equals(Object obj) {if (this == obj)return true;if (obj == null)return false;if (getClass() != obj.getClass())return false;final ReflectPoint other = (ReflectPoint) obj;if (x != other.x)return false;if (y != other.y)return false;return true;}}
public class ReflectTest1{public static void main(String[] args){Collection al=new ArrayList();ReflectPoint rp1=new ReflectPoint(3,3);ReflectPoint rp2=new ReflectPoint(5,6);ReflectPoint rp3=new ReflectPoint(3,3);al.add(rp1);al.add(rp2);al.add(rp3);al.add(rp1);System.out.println("list:"+al.size());//list:4Collection hs=new HashSet();hs.add(rp1);hs.add(rp2);hs.add(rp3);hs.add(rp1);//重寫了hashCode方法和equals方法,rp1重複添加了,只添加一個rp1,rp1和rp3也重複,不添加rp3System.out.println("hs:"+hs.size());//hs:2 [集合記憶體放的是rp1和rp2]System.out.println(hs);//[3 3, 5 6] //集合中添加了元素rp1後,修改對象rp1的成員變數值,這個成員變數是參與了hashCode()值的運算,進行移除rp1操作rp1.x=100;hs.remove(rp1);//移除元素//發現還是2個元素,remove方法因為雜湊值被修改了,無法移除原來的rp1對象,造成記憶體泄露!!System.out.println(hs);}}