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

java – 自动装箱:所以我可以写:整数i = 0;而不是:Integer i

发布时间:2020-12-14 05:29:23 所属栏目:Java 来源:网络整理
导读:自动装箱似乎归结于我可以写的事实: Integer i = 0; 代替: Integer i = new Integer(0); 因此,编译器可以自动将原语转换为对象. 是这个想法吗?为什么这很重要? 解决方法 你有点简化了一点. 使用集合时,自动装箱也会起作用.如sun的java文档中所述: Colle
自动装箱似乎归结于我可以写的事实:
Integer i = 0;

代替:

Integer i = new Integer(0);

因此,编译器可以自动将原语转换为对象.

是这个想法吗?为什么这很重要?

解决方法

你有点简化了一点.

使用集合时,自动装箱也会起作用.如sun的java文档中所述:

Collections can only hold object references,so you have to box primitive values into the appropriate wrapper class. When you take the object out of the collection,you get the Integer that you put in; if you need an int,you must unbox the Integer using the intValue method. All of this boxing and unboxing is a pain,and clutters up your code. The autoboxing and unboxing feature automates the process,eliminating the pain and the clutter.

So when should you use autoboxing and unboxing? Use them only when there is an “impedance mismatch” between reference types and primitives,for example,when you have to put numerical values into a collection. It is not appropriate to use autoboxing and unboxing for scientific computing,or other performance-sensitive numerical code. An Integer is not a substitute for an int; autoboxing and unboxing blur the distinction between primitive types and reference types,but they do not eliminate it.

Great overview of Autoboxing

(编辑:李大同)

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

    推荐文章
      热点阅读