java 基礎筆記--hashCode(),你好,為啥要重寫

來源:互聯網
上載者:User

標籤: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(),你好,為啥要重寫

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.