java 在谷歌集合中静态初始化地图的最佳方式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12218345/
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
The best way to static initialization of Maps in google collections
提问by Nawa
What is the best way to static initialization of modifiable Maps? I found only
静态初始化可修改地图的最佳方法是什么?我发现只有
ImmutableMap.of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5)
But this way created immutable map and contains fixed list of parameters.
但是这种方式创建了不可变的映射并包含固定的参数列表。
回答by u290629
If you do want an of
code fashion, you could use:
如果你确实想要一种of
代码时尚,你可以使用:
myMap = Maps.newHashMap(ImmutableMap.of(k1, v1, k2, v2...));
In addition, ImmutableMap.Builder
is other choice to create a Map from complex source:
此外,ImmutableMap.Builder
从复杂源创建 Map 的其他选择是:
myMap = Maps.newHashMap(new ImmutableMap.Builder<K, V>()
.put(k1, v1) //One k-v pair
.putAll(otherMap) //From other Map
.put(Maps.immutableEntry(k2, v3)) //From a Map Entry
...
.build());
Plus: My code is not original intention of ImmutableMap. If Nawa insists on using Guava library ;)
加:我的代码不是 ImmutableMap 的初衷。如果 Nawa 坚持使用 Guava 库;)
回答by Frank Pavageau
You don't actually need static initialization. What's wrong with the following ?
您实际上并不需要静态初始化。以下有什么问题?
Map<K, V> map = Maps.newHashMap();
map.put(k1, v1);
map.put(k2, v2);
// More put() calls
// map is now ready to use.
You can create a helper method around it if needed, but you can only create so many different versions (for 1 entry, 2 entries, etc.). At some point it's not helping anymore.
如果需要,您可以围绕它创建一个辅助方法,但您只能创建这么多不同的版本(1 个条目、2 个条目等)。在某些时候,它不再有帮助。
回答by Fabian Barney
There is no point in having this for mutable collections. The only reason I can think of is that you want to have a shorthand for this when creating initially small mutable maps. Write your own utility methods if you need this quiet often:
对可变集合使用这个是没有意义的。我能想到的唯一原因是您希望在创建最初的小型可变映射时对此有一个简写。如果您经常需要安静,请编写您自己的实用程序方法:
public static <K,V> HashMap<K,V> newHashMap(K k1, V v1) {
HashMap<K, V> map = new HashMap<>();
map.put(k1, v1);
return map;
}
public static <K,V> HashMap<K,V> newHashMap(K k1, V v1, K k2, V v2) {
HashMap<K, V> map = new HashMap<>();
map.put(k1, v1);
map.put(k2, v2);
return map;
}
...
Override it as long as you think it is still readable. Because of mixture from keys and values this gets unreadable fast in my opinion - even with proper formatting. Guava guys stopped this at 5 key-value pairs what is too much imho.
只要您认为它仍然可读,就可以覆盖它。由于键和值的混合,我认为这会很快变得不可读——即使格式正确。番石榴家伙在 5 个键值对处停止了这个,恕我直言太多了。