hashCode和identityHashCode

參考網頁

https://www.jianshu.com/p/ebf4d0b142acjava

hashCode參見

http://www.javashuo.com/article/p-wdjirvcg-cc.htmlide

identityHashCode:返回對象的hashCode,無論對象是否重寫hashCode方法

identityHashCode是System裏面提供的本地方法,java.lang.System#identityHashCode。this

/**

 * Returns the same hash code for the given object as

 * would be returned by the default method hashCode(),

 * whether or not the given object's class overrides

 * hashCode().

 * The hash code for the null reference is zero.

 *

 * @param x object for which the hashCode is to be calculated

 * @return  the hashCode

 * @since   JDK1.1

 */

public static native int identityHashCode(Object x);

identityHashCode和hashCode的區別是,identityHashCode會返回對象的hashCode,而無論對象是否重寫了hashCode方法。spa

試驗

示例代碼

public class StringTest {
    public static void main(String[] args) {
        String str1 = new String("abc");
        String str2 = new String("abc");
        System.out.println("str1 hashCode: " + str1.hashCode());
        System.out.println("str2 hashCode: " + str2.hashCode());
        System.out.println("str1 identityHashCode: " + System.identityHashCode(str1));
        System.out.println("str2 identityHashCode: " + System.identityHashCode(str2));

        People user = new People("test", 1);
        System.out.println("user hashCode: " + user.hashCode());
        System.out.println("user identityHashCode: " + System.identityHashCode(user));
    }
}

class People{

    public People(String name,int age){
        this.name = name;
        this.age = age;
    }
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    private String name;
    private int age;
}

運行結果

str1 hashCode: 96354.net

str2 hashCode: 96354code

str1 identityHashCode: 312116338對象

str2 identityHashCode: 453211571blog

user hashCode: 757108857內存

user identityHashCode: 757108857get

結果分析

一、str1和str2的hashCode是相同的,是由於String類重寫了hashCode方法,它根據String的值來肯定hashCode的值,因此只要值同樣,hashCode就會同樣。

二、str1和str2的identityHashCode不同,雖然String重寫了hashCode方法,identityHashCode永遠返回根據對象物理內存地址產生的hash值,因此每一個String對象的物理地址不同,identityHashCode也會不同。

三、People對象沒重寫hashCode方法,因此hashCode和identityHashCode返回的值同樣。

總結

hashCode方法能夠被重寫並返回重寫後的值,identityHashCode會返回對象的hash值而無論對象是否重寫了hashCode方法。

相關文章
相關標籤/搜索