问题描述
有一些实用方法来创建 ImmutableMap
如 Immutable.of(Key,value)
及其重载。
但是对于 HashMap
或 LinkedHashMap
,此类方法不存在地图
类。
有没有更好的方法做这件事,或Guava假设这样的地图总是一个不变的地图, ImmutableMap
是最好的选择不需要为 HashMap
提供实用程序。
There are utility methods to create ImmutableMap
like Immutable.of(Key, value)
and its overload.
But such methods don't exist for HashMap
or LinkedHashMap
in Maps
class.
Is there any better way to do this or Guava assumes such a map is always a constant map and ImmutableMap
is best option to go with and don't need to provide a utility for HashMap
.
推荐答案
为什么要使用常规的 HashMap
或 LinkedHashMap
?您只需这样做:
Why would you want those for a regular HashMap
or LinkedHashMap
? You can just do this:
Map<String, Object> map = Maps.newHashMap();
map.put(key, value);
ImmutableMap
有点更麻烦创造;您首先需要创建一个 Builder
,然后将键值对放在构建器中,然后调用 build()
就可以创建你的 ImmutableMap
。 ImmutableMap.of()
方法缩短了写入的时间,如果你想用一个键创建一个 ImmutableMap
值对。
The thing with ImmutableMap
is that it is a little bit more cumbersome to create; you first need to make a Builder
, then put the key-value pairs in the builder and then call build()
on it to create your ImmutableMap
. The ImmutableMap.of()
method makes it shorter to write if you want to create an ImmutableMap
with a single key-value pair.
考虑如果不使用 ImmutableMap.of()
方法:
ImmutableMap<String, Object> map = ImmutableMap.builder()
.put(key, value);
.build();
这篇关于在地图中的HashMap ImmutableMap.of()解决方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!