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的源码里,写到:

  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

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值