Java 映射和原语
我想创建一个以 String
作为键、以 primitive 作为值的映射。我正在查看 Java 文档,但没有看到 Primitive 是一种类类型,或者它们共享某种包装类。
如何将值限制为原始值?
Map<字符串,基元> map = new HashMap
I want to create a mapping that takes a String
as the key and a primitive as the value. I was looking at the Java docs and did not see that Primitive was a class type, or that they shared some kind of wrapping class.
How can I constrain the value to be a primitive?
Map<String, Primitive> map = new HashMap<String, Primitive>();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
Java Autoboxing 允许在
Long、Integer、Double
,然后使用原始值对它们进行操作。例如:如果您想在一个映射中存储不同的基本类型,您可以通过创建一个
Map
来实现。允许存储BigDecimal
、BigInteger
、Byte
、Double
、Float
、Integer
、Long
、Short
(以及AtomicLong
、AtomicInteger
)。这是一个例子:
Java Autoboxing allows to create maps on
Long, Integer, Double
and then operate them using primitive values. For example:If you want to store in one map different primitive types, you can to it by making a
Map<String, Number>
. Allows to store values ofBigDecimal
,BigInteger
,Byte
,Double
,Float
,Integer
,Long
,Short
(andAtomicLong
,AtomicInteger
).Here is an example:
谷歌搜索“Java Primitive Maps”,您会发现一些专门的类型,可以避免自动装箱的需要。一个例子是: https://labs.carrotsearch.com/hppc.html
但是,一般来说,您应该像其他答案中提到的那样使用自动装箱。
Google for "Java Primitive Maps" and you will find some specialised types which avoid the need for autoboxing. An example of this is: https://labs.carrotsearch.com/hppc.html
However, in general you should do fine with autoboxing as mentioned in other answers.
您可以执行以下操作:
然后像这样的操作
将起作用。基元
1
将自动装箱为Integer
。同样:也会起作用,因为
Integer
将自动拆箱为int
。查看有关自动装箱和自动拆箱的一些文档。
You can do the following:
Then operations like:
will work. The primitive
1
will get auto-boxed into anInteger
. Likewise:will also work because the
Integer
will get auto-unboxed into anint
.Check out some documentation on autoboxing and autounboxing.
每个原语都有一个包装类,例如
java.lang. lang.Long
表示long
。因此,您可以将包装类映射到
String
,如果您使用 Java 1.5+,只需将原语放入映射即可:Every primitive has a wrapper class, like
java.lang.Long
forlong
.So you can map the the wrapper class to
String
and, if you use Java 1.5+, simply put primitives to the map:你会使用他们的盒装对应物。
Integer 是原始 int 的不可变装箱类型。还有类似的 Short、Long、Double、Float 和 Byte 装箱类型。
You would use their boxed counterpart.
Integer is an immutable boxed type of the primitive int. There are similar Short, Long, Double, Float and Byte boxed types.
如果出于性能原因需要将该值设为基元,可以使用 TObjectIntHashMap 或类似的。
例如
与 Map的一个区别是值是 int 基元类型而不是 Integer 对象类型。
If you need the value to be a primitive for performance reasons, you can use TObjectIntHashMap or similar.
e.g.
One difference with Map<String, Integer> is that the values are of type int primitive rather than Integer object.
您不能将基元作为
Map
接口中的键或值。相反,您可以使用包装类,例如Integer
、Character
、Boolean
等。阅读wiki了解更多信息。
You can't have a primitive as key or value in
Map
interface. Instead you can use Wrapper classes, likeInteger
,Character
,Boolean
and so on.Read more on wiki.