Java:自动装箱和强制转换有什么区别?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/501653/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java: What's the difference between autoboxing and casting?
提问by nzpcmad
This questionis about "Why does autoboxing make some calls ambiguous in Java?"
这个问题是关于“为什么自动装箱使 Java 中的某些调用变得模棱两可?”
But reading through the answers, there are a number of references to casting and I'm not sure I completely understand the difference.
但是仔细阅读答案,有很多关于演员的参考资料,我不确定我是否完全理解其中的区别。
Can someone provide a simple explanation?
有人可以提供一个简单的解释吗?
采纳答案by cmsjr
Boxing is when you convert a primitive type to a reference type, un-boxing is the reverse. Casting is when you want one type to be treated as another type, between primitive types and reference types this means an implicit or explicit boxing operation. Whether it needs to be explicit is a language feature.
装箱是将原始类型转换为引用类型,而取消装箱则相反。强制转换是当您希望将一种类型视为另一种类型时,在原始类型和引用类型之间,这意味着隐式或显式装箱操作。是否需要显式是语言特性。
回答by cletus
List<String> list = (List<String>)object;
is a cast.
是演员表。
void doSomething(Integer i) { ... }
...
doSomeething(5);
is auto-boxing.
是自动装箱。
Integer getSomething();
...
int i = getSomething();
is auto-unboxing.
是自动开箱。
回答by Fortyrunner
Autoboxing was introduced in Java 5 to prevent code such as :
Java 5 中引入了自动装箱以防止以下代码:
map.put("ABC", new Integer(5));
map.put("DEF", new Integer(6));
You can now say :
你现在可以说:
map.put("ABC", 5);
Whilst its easier - it does have a few pitfalls if you aren't completely sure of what you are doing.
虽然它更容易 - 如果您不完全确定自己在做什么,它确实有一些陷阱。
回答by John Nilsson
Boxing is wrapping a value inside a container, such as an int primitive value inside an Integer object
装箱是将一个值包装在一个容器中,例如在一个 Integer 对象中包装一个 int 原始值
Casting is just how to look at the type.
铸造只是如何看待类型。
The former produces another kind of value, the later just modifies how to treat an already existing value
前者产生另一种值,后者只是修改如何对待一个已经存在的值
Except casting between primitive types actually modifies their representation. (This doesn't make it clearer does it?)
除了基本类型之间的转换实际上修改了它们的表示。(这样不是说得更清楚了吗?)
回答by eljenso
Boxing and unboxing is a type of cast in Java, where you cast from a primitive to its wrapper class or the inverse, e.g. boolean to Boolean (box), or Boolean to boolean (unbox).
装箱和拆箱是 Java 中的一种类型转换,您可以在其中从原始类型转换为其包装类或反向转换,例如布尔值转换为布尔值(框),或布尔值转换为布尔值(取消装箱)。
Types of casts in Java, with example:
Java 中的类型转换,例如:
an identity conversion (§5.1.1) String to String
a widening primitive conversion (§5.1.2) byte to int
a narrowing primitive conversion (§5.1.3) int to byte
a widening reference conversion (§5.1.5) Integer to Number
a narrowing reference conversion (§5.1.6) Number to Integer
a boxing conversion (§5.1.7) int to Integer
an unboxing conversion (§5.1.8). Integer to int
身份转换(第 5.1.1 节)字符串到字符串
扩展原始转换(第 5.1.2 节)字节到 int
缩小原始转换(第 5.1.3 节)int 到字节
扩大参考转换(第 5.1.5 节)整数到数字
缩小参考转换(第 5.1.6 节)数字到整数
将 int 转换为 Integer 的拳击转换(第 5.1.7 节)
拆箱转换(第 5.1.8 节)。整数转int
Autoboxing or autounboxing happens when the compiler does the boxing/unboxing conversion for you (it doesn't explicitly appear in the source code as a cast expression), e.g. see the question you referred to.
自动装箱或自动拆箱发生在编译器为您进行装箱/拆箱转换时(它没有明确地作为转换表达式出现在源代码中),例如,请参阅您提到的问题。
回答by joel.neely
Both casting and boxing/unboxing have to do with types and apparent (or real) conversion, but boxing/unboxing is specific to the relationship between primitive types and their corresponding wrapper types, while casting is the term for explicit or implicit change of type in the more general sense.
强制转换和装箱/拆箱都与类型和表观(或实数)转换有关,但装箱/拆箱特定于原始类型与其对应的包装类型之间的关系,而强制转换是显式或隐式更改类型的术语更普遍的意义。
Castingis a general term with two related-but-different meanings:
铸造是一个通用术语,具有两个相关但不同的含义:
Treating a value of one type as ifit were a value of another type. Two examples of this first usages are:
1.1. Given that class
Bextends classA, you can ask formyBan instance ofBto be treated as an instance ofAby writing((A) myB)wherever a reference to an instance ofAcould appear. This doesn't actually produce a new instance ofA.1.2. Pre-Java5 collections stored all content as
Object; this usually required you to use a cast after retrieving an object from a collection. For example, if you had stored aStringin aMapand needed to get its length, you'd write something like((String) myMap.get(someKey)).length()where the cast would be required in order to call thelengthmethod ofString. Again, this doesn't cause a newStringto be created.Explicitly convertingone type to another (i.e. explicitly changing the representation). An example of this second usage is in the expression
((int) (float_var + 0.5F))which rounds a floating-point variable by adding 0.5 (which produces a floating-point value) and then explicitly converting that value to an integer. The resulting integer value (after the(int)cast) is producedfrom the other value by internal computation.
将一种类型的值视为另一种类型的值。第一种用法的两个示例是:
1.1. 鉴于该类
B扩展了 classA,您可以通过在可能出现对实例的引用的任何地方写入来要求将myB的实例B视为 的实例。这实际上不会产生.A((A) myB)AA1.2. Java5 之前的集合将所有内容存储为
Object; 这通常要求您在从集合中检索对象后使用强制转换。例如,如果您已将 a 存储String在 a 中Map并需要获取其长度,则您将编写类似于((String) myMap.get(someKey)).length()需要强制转换的地方以调用 的length方法String。同样,这不会导致String创建新的。将一种类型显式转换为另一种类型(即显式更改表示)。第二种用法的一个例子是在表达式中
((int) (float_var + 0.5F)),它通过添加 0.5(产生一个浮点值)来舍入一个浮点变量,然后将该值显式转换为一个整数。结果整数值(在转换之后(int))是通过内部计算从另一个值产生的。
Casting can be done when there's a superclass/subclass or interface/implementor relationship (meaning 1 above) or when the two types are primitive numeric types (meaning 2). You might look up "widening" and "narrowing" for more detail.
当存在超类/子类或接口/实现器关系(上面的含义 1)或当这两种类型是原始数字类型(含义 2)时,可以进行转换。您可以查找“扩大”和“缩小”以获取更多详细信息。
Boxingrefers to wrapping primitive types in container objects, usually only done when you must have an object (e.g. storing a value in a collection). The primitive and wrapper types come in pairs:
装箱是指将原始类型包装在容器对象中,通常仅在您必须拥有一个对象时才执行(例如,将值存储在集合中)。原始类型和包装类型成对出现:
int Integer
long Long
boolean Boolean
... ...
Unboxingsimply means retrieving the primitive value from within its object wrapper.
拆箱只是意味着从其对象包装器中检索原始值。
As of Java5, when you write an expression that uses a primitive value where the corresponding wrapper type would be required (such as putting an integer into a collection), the compiler automagically slips in the code that actually wraps that primitive value. Likewise it will provide the unwrapping code for you.
从 Java5 开始,当您编写使用原始值的表达式时,需要相应的包装类型(例如将整数放入集合中),编译器会自动插入实际包装该原始值的代码。同样,它会为您提供解包代码。
So instead of writing (in pre-Java5) something like:
因此,而不是编写(在 Java5 之前)类似的内容:
Map myMap = new HashMap();
...
myMap.put(someKey,Integer.valueOf(3));
...
int nextValue = (myMap.get(someKey)).intValue() + 1;
you can write:
你可以写:
Map<KeyType,Integer> myMap = new HashMap<KeyType,Integer>();
...
myMap.put(someKey,3);
...
int nextValue = myMap.get(someKey) + 1;
and the boxing/unboxing code is inserted by the compiler.
并且装箱/拆箱代码由编译器插入。
回答by Balasubramanian Jayaraman
Does Autoboxing and Unboxing can be applied in the following case ?
自动装箱和拆箱可以应用于以下情况吗?
Long one = 10;
long two = 15;
Long three = 20;
if(one == three) //will this be unboxed or do we need to put a explicit
//condition like if(one.intValue() == three.intValue())
System.out.println("Equal");
else
System.out.println("Not Equal");
if(one == two) //will this be unboxed or do we need to put a explicit
//condition like if(one.intValue() == two)
System.out.println("Equal");
else
System.out.println("Not Equal");

