標籤:strong gen none 參考 pen 一個 重寫 code 定義
從學習java開始就知道,hashCode()方法是object類本身就有的方法,所有的類都繼承了object,也就了hashCode()這個方法。
在學java的時候,就被告知在重寫equals方法時,也要重寫hashCode方法。當時沒細想,以為這個是文法規定。
後來瞭解到,這個確實java規定:
hashcode相等的兩個對象內容不一定相等。
對象內容相等的兩個對象hashcode一定相等!
如果比較兩個對象是否相等。比較兩個對象的內容涉及的東西比較多,但是hashcode只是一個int數字,要比較還是不簡單!效能上比equals快多了。在set,map等集合類中,代碼中都是先利用hashcode判斷key是否存在和重複。這也就是如果自訂類作為key時,要求要重寫hashCode方法。
預設的hashcode的值是對象在記憶體中的地址。
隨便提一下,String也是重寫了hashCode方法的。
String類關鍵代碼如下:
/** * Returns a hash code for this string. The hash code for a * {@code String} object is computed as * <blockquote><pre> * s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1] * </pre></blockquote> * using {@code int} arithmetic, where {@code s[i]} is the * <i>i</i>th character of the string, {@code n} is the length of * the string, and {@code ^} indicates exponentiation. * (The hash value of the empty string is zero.) * * @return a hash code value for this object. */ public int hashCode() { int h = hash; if (h == 0 && value.length > 0) { char val[] = value; for (int i = 0; i < value.length; i++) { h = 31 * h + val[i]; } hash = h; } return h; }View Code
就是它了,根據內容來決定hashcode的值的。
測試代碼如下:
public class Dog { private int age; private String name; public Dog(String name,int age){ this.name=name; this.age=age; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
public class Hash { public static void main(String[] args) { // TODO Auto-generated method stub String a="abc"; String b=new String("abc"); String c=new String("abc"); String d="abc"; System.out.println(" a hashcode:"+a.hashCode()+"--"+(a==d)); System.out.println(" b hashcode:"+b.hashCode()+"--"+(b==c)); System.out.println("c hashcode:"+c.hashCode()); System.out.println("d hashcode:" +d.hashCode()); Dog dog1=new Dog("aa", 1); Dog dog2=new Dog("aa", 1); System.out.println(dog1.hashCode()); System.out.println(dog2.hashCode()); }}
運行結果(每次運行dog的hashcode的結果不一樣。僅僅是參考):
java 基礎筆記--hashCode(),你好,為啥要重寫