[英]Difference between putting primitive or object to an object map in Java
I have a simple map: 我有一张简单的地图:
Map<String, Object> myMap;
And I am just wondering, what is the difference between these two solutions: First, when I put my double
value as a Double
object: 我只是想知道,这两种解决方案之间有什么区别:首先,当我将
double
值作为Double
对象放置时:
myMap.put("object", Double.valueOf(myPrimitiveDouble));
Second when I put my double
value as a primitive type: 其次,当我将
double
值用作原始类型时:
myMap.put("primitive", myPrimitiveDouble);
I think the first one is unnecessary, am I right? 我认为第一个是不必要的,对吗? Thanks for the answers!
感谢您的回答!
When you put your primitive double
as a value into your Map<String, Object>
, it will automatically be boxed into a Double
type, as generic collections (that includes maps) do not use primitives. 当您将基本
double
精度值作为值放入Map<String, Object>
,它会自动装箱成Double
类型,因为通用集合(包括映射)不使用基元。
This is called autoboxing . 这称为自动装箱 。
Therefore, the Double.valueOf
invocation is indeed redundant in this case. 因此,在这种情况下,
Double.valueOf
调用确实是多余的。
Example 例
Map<String, Object> myMap = new HashMap<>();
double foo = 5;
myMap.put("", foo);
System.out.println(myMap.get("").getClass());
Output 产量
class java.lang.Double
Note 注意
Java will auto-box your primitive double
to Double
when the collection is parametrized with either Object
, Number
or Double
. Java将自动框中输入原始
double
到Double
集合时与任一参数化的Object
, Number
或Double
。
Your code would not compile, however, if your map values were parametrized with an incompatible type, eg Integer
. 但是,如果使用不兼容的类型(例如
Integer
对映射值进行了参数化,则您的代码将无法编译。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.