java 使用原始 double 值初始化 Double 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3290681/
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
Initializing a Double object with a primitive double value
提问by Doug Porter
What is happening when a java.lang.Double object is initialized without using a call to the constructor but instead using a primitive? It appears to work but I'm not quite sure why. Is there some kind of implicit conversion going on with the compiler? This is using Java 5.
当 java.lang.Double 对象在不使用构造函数调用而是使用原语初始化时会发生什么?它似乎有效,但我不太确定为什么。编译器是否正在进行某种隐式转换?这是使用Java 5。
public class Foo {
public static void main(String[] args) {
Double d = 5.1;
System.out.println(d.toString());
}
}
回答by krock
This is called Autoboxingwhich is a feature that was added in Java 5. It will automatically convert between primitive types and the wrapper types such as double(the primitive) and java.lang.Double(the object wrapper). The java compiler automatically transforms the line:
这称为自动装箱,这是 Java 5 中添加的一项功能。它将自动在原始类型和包装器类型(例如double(原始)和java.lang.Double(对象包装器)之间进行转换)。java 编译器自动转换该行:
Double d = 5.1;
into:
进入:
Double d = Double.valueOf(5.1);
回答by willcodejavaforfood
It is called AutoBoxing
它被称为自动装箱
Autoboxing and Auto-Unboxing of Primitive Types Converting between primitive types, like int, boolean, and their equivalent Object-based counterparts like Integer and Boolean, can require unnecessary amounts of extra coding, especially if the conversion is only needed for a method call to the Collections API, for example.
The autoboxing and auto-unboxing of Java primitives produces code that is more concise and easier to follow. In the next example an int is being stored and then retrieved from an ArrayList. The 5.0 version leaves the conversion required to transition to an Integer and back to the compiler.
原始类型的自动装箱和自动拆箱 在原始类型(如 int、boolean 和它们等效的基于对象的对应物(如 Integer 和 Boolean)之间进行转换可能需要进行不必要的额外编码,特别是如果转换仅用于调用例如,集合 API。
Java 原语的自动装箱和自动拆箱产生更简洁、更易于遵循的代码。在下一个示例中,将存储一个 int,然后从 ArrayList 中检索它。5.0 版本保留了转换为整数并返回到编译器所需的转换。
Before
前
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(0, new Integer(42));
int total = (list.get(0)).intValue();
After
后
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(0, 42);
int total = list.get(0);
回答by Matt Ball
It's called autoboxing.
这叫做自动装箱。

