加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Java中的Boxing和AutoBoxing有什么区别?

发布时间:2020-12-14 23:58:49 所属栏目:Java 来源:网络整理
导读:Java中的Boxing和AutoBoxing有什么区别?一些Java认证书使用了两个这样的术语.他们是指与Boxing相同的东西吗? 解决方法 拳击是机制(即从int到Integer); autoboxing是编译器的功能,通过它可以为您生成装箱代码. 例如,如果你写代码: // list is a ListIntege
Java中的Boxing和AutoBoxing有什么区别?一些Java认证书使用了两个这样的术语.他们是指与Boxing相同的东西吗?

解决方法

拳击是机制(即从int到Integer); autoboxing是编译器的功能,通过它可以为您生成装箱代码.

例如,如果你写代码:

// list is a List<Integer>
list.add(3);

然后编译器会自动为您生成装箱代码;代码中的“最终结果”将是:

list.add(Integer.valueOf(3));

关于为什么Integer.valueOf()而不是新的Integer()的说明:基本上,因为JLS这么说:)引用section 5.1.7:

If the value p being boxed is true,false,a byte,or a char in the
range u0000 to u007f,or an int or short number between -128 and 127
(inclusive)
,then let r1 and r2 be the results of any two boxing
conversions of p. It is always the case that r1 == r2.

如果您使用“仅仅”构造函数,则无法强制执行此要求.工厂方法,如Integer.valueOf(),可以.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读