How can I initialise a static Map?

前端 未结 30 1013
慢半拍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:36

    JEP 269 provides some convenience factory methods for Collections API. This factory methods are not in current Java version, which is 8, but are planned for Java 9 release.

    For Map there are two factory methods: of and ofEntries. Using of, you can pass alternating key/value pairs. For example, in order to create a Map like {age: 27, major: cs}:

    Map info = Map.of("age", 27, "major", "cs");
    

    Currently there are ten overloaded versions for of, so you can create a map containing ten key/value pairs. If you don't like this limitation or alternating key/values, you can use ofEntries:

    Map info = Map.ofEntries(
                    Map.entry("age", 27),
                    Map.entry("major", "cs")
    );
    

    Both of and ofEntries will return an immutable Map, so you can't change their elements after construction. You can try out these features using JDK 9 Early Access.

提交回复
热议问题