How can I initialise a static Map?

前端 未结 30 1051
慢半拍i
慢半拍i 2020-11-22 08:43

How would you initialise a static Map in Java?

Method one: static initialiser
Method two: instance initialiser (anonymous subclass) or some other m

30条回答
  •  花落未央
    2020-11-22 09:31

    I've read the answers and i decided to write my own map builder. Feel free to copy-paste and enjoy.

    import java.util.Collections;
    import java.util.HashMap;
    import java.util.Map;
    
    /**
     * A tool for easy creation of a map. Code example:
    * {@code MapBuilder.of("name", "Forrest").and("surname", "Gump").build()} * @param key type (inferred by constructor) * @param value type (inferred by constructor) * @author Vlasec (for http://stackoverflow.com/a/30345279/1977151) */ public class MapBuilder { private Map map = new HashMap<>(); /** Constructor that also enters the first entry. */ private MapBuilder(K key, V value) { and(key, value); } /** Factory method that creates the builder and enters the first entry. */ public static MapBuilder mapOf(A key, B value) { return new MapBuilder<>(key, value); } /** Puts the key-value pair to the map and returns itself for method chaining */ public MapBuilder and(K key, V value) { map.put(key, value); return this; } /** * If no reference to builder is kept and both the key and value types are immutable, * the resulting map is immutable. * @return contents of MapBuilder as an unmodifiable map. */ public Map build() { return Collections.unmodifiableMap(map); } }

    EDIT: Lately, I keep finding public static method of pretty often and I kinda like it. I added it into the code and made the constructor private, thus switching to static factory method pattern.

    EDIT2: Even more recently, I no longer like static method called of, as it looks pretty bad when using static imports. I renamed it to mapOf instead, making it more suitable for static imports.

提交回复
热议问题