Autoboxing:所以我可以写:Integer i = 0;而不是:Integer i = new Integer(0); [英] Autoboxing: So I can write: Integer i = 0; instead of: Integer i = new Integer(0);

查看:426
本文介绍了Autoboxing:所以我可以写:Integer i = 0;而不是:Integer i = new Integer(0);的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Autoboxing似乎归结为我可以写的事实:

Autoboxing seems to come down to the fact that I can write:

Integer i = 0; 

而不是:

Integer i = new Integer(0);

因此,编译器可以自动将基元转换为Object。

So, the compiler can automatically convert a primitive to an Object.

这是个主意吗?为什么这很重要?

Is that the idea? Why is this important?

推荐答案

你有点简化它。

使用集合时,自动装箱也会发挥作用。正如sun的java文档中所解释的那样:


集合只能保存对象引用,因此您必须将原始值设置为适当的值包装类。 ... 当您将对象从集合中取出时,您将获得放入的Integer;如果需要int,则必须使用intValue方法取消对Integer的装箱。所有这些装箱和拆箱都是一种痛苦,并使你的代码变得混乱。自动装箱和拆箱功能可自动完成整个过程,消除痛苦和杂乱。

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.

那么什么时候应该使用自动装箱和拆箱?仅在引用类型和基元之间存在阻抗不匹配时才使用它们,例如,当您必须将数值放入集合时。将自动装箱和拆箱用于科学计算或其他对性能敏感的数字代码是不合适的。 Integer不能替代int; autoboxing和unboxing模糊了原始类型和引用类型之间的区别,但它们并没有消除它。

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.

Autoboxing的概述

这篇关于Autoboxing:所以我可以写:Integer i = 0;而不是:Integer i = new Integer(0);的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆