参考网页

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

hashCode参见

https://my.oschina.net/u/3866531/blog/3008217

identityHashCode:返回对象的hashCode,不管对象是否重写hashCode方法

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

/**

 * 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方法。

试验

示例代码

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

str2 hashCode: 96354

str1 identityHashCode: 312116338

str2 identityHashCode: 453211571

user hashCode: 757108857

user identityHashCode: 757108857

结果分析

1、str1和str2的hashCode是相同的,是因为String类重写了hashCode方法,它根据String的值来确定hashCode的值,所以只要值一样,hashCode就会一样。

2、str1和str2的identityHashCode不一样,虽然String重写了hashCode方法,identityHashCode永远返回根据对象物理内存地址产生的hash值,所以每个String对象的物理地址不一样,identityHashCode也会不一样。

3、People对象没重写hashCode方法,所以hashCode和identityHashCode返回的值一样。

总结

hashCode方法可以被重写并返回重写后的值,identityHashCode会返回对象的hash值而不管对象是否重写了hashCode方法。

02-02 07:08