简体   繁体   中英

The best way to static initialization of Maps in google collections

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.

If you do want an of code fashion, you could use:

myMap = Maps.newHashMap(ImmutableMap.of(k1, v1, k2, v2...));

In addition, ImmutableMap.Builder is other choice to create a Map from complex source:

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 ;)

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM