简体   繁体   English

在Java中将基元或对象放入对象映射之间的区别

[英]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将自动框中输入原始doubleDouble集合时与任一参数化的ObjectNumberDouble

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.

相关问题 在Java中将对象和原始数据作为参数传递有什么区别? - what is the difference between passing an object and a primitive data as the parameter in Java? Java中的long对象和基本类型long之间有什么区别? - What is difference between Long object and primitive type long in Java? 将JSON原语映射到Java中的对象值 - Map JSON primitive to object value in Java 地图之间的区别 <?,?> 和地图 <Object,Object> - difference between Map<?,?> and Map<Object,Object> 原始Java Map的对象哈希映射(将POJO映射到Map) - Object Hash Mapping for a primitive Java Map (Mapping POJO's into Map) 返回对象/基元和仅调用它之间的区别 - The difference between returning a object/primitive and just simply calling it Java-“返回对象”和“返回(对象)”之间的区别 - Java - Difference between “return object” and “return (object)” In Java, how to compare two object and return Map or Xml, Json of properties which is the difference between two object? - In Java, how to compare two object and return Map or Xml, Json of properties which is the difference between two object? Map有区别吗<string,object>和 Java object 在 json 序列化之后?</string,object> - Is there any difference between Map<String,Object> and Java object after json serialization? 将配置定义为 Properties 和 Map object 之间的区别 - Difference between defining configuration as Properties and Map object
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM