Integer.class与int.class与Inte.TYPE

一、Integer.class与int.class

Integer.class 是Integer类型的类对象,类似的,int.class是是int类型的类对象。

作为一个特例,基本类型都有一个类对象,主要是用在反射中。

Integer.TYPE 和 int.class 是等价的。

public static void main(String[] args) {
    Class<Integer> a = int.class;
    Class<Integer> b = Integer.TYPE;
    Class<Integer> c = Integer.class;

    System.out.println(System.identityHashCode(a));
    System.out.println(System.identityHashCode(b));
    System.out.println(System.identityHashCode(c));   
}

输出结果为:

1670675563
1670675563
723074861

二、System.identityHashCode与Object.hashcode

int.class与Integer.TYPE是等价的,但是与Integer.class是不相等的,

作为一个特例,基本类型都有一个类对象,主要是用在反射中。
Integer.class与int.class与Inte.TYPE_第1张图片
在Integer的源码里,写到:

  public static final Class<Integer>  TYPE = (Class<Integer>) Class.getPrimitiveClass("int");

这里System.identityHashCode 跟调用 hashcode是一样的效果,那这俩有啥区别?

/**
 * 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);
  1. 首先,System.identityHashCode(nullReference) 会返回0,但是 nullReference.hashCode() 会报错NullPointerException

  2. 然后,如果我们重写了hashcode(),比如:

@Override
public int hashCode() {
    return 0xAAAABBBB;
}

hashcode()的结果都是一样的hashcode,但是如果调用 System.identityHashCode,结果还是不一样的.

  1. System.identityHashCode()也能传入基本类型,会进行自动包装。

更多identityHashCode的细节参考 https://www.jianshu.com/p/24fa4bdb9b9d

你可能感兴趣的:(知识点扫盲,java)