C# to Java - Dictionaries?

后端 未结 5 1210
伪装坚强ぢ
伪装坚强ぢ 2020-12-25 09:41

Is it possible in Java to make a Dictionary with the items already declared inside it? Just like the below C# code:

   Dictionary d = new          


        
5条回答
  •  孤独总比滥情好
    2020-12-25 10:37

    This will do what you want:

    Map map = new HashMap(){{
        put("cat", 2);
        put("dog", 1);
        put("llama", 0);
        put("iguana", -1);
    }};
    

    This statement creates an anonymous subclass of HashMap, where the only difference from the parent class is that the 4 entries are added during instance creation. It's a fairly common idiom in the Java world (although some find it controversial because it creates a new class definition).

    Because of this controversy, as of Java 9 there is a new idiom for conveniently constructing maps: the family of static Map.of methods.

    With Java 9 or higher you can create the map you need as follows:

    Map map = Map.of(
        "cat", 2,
        "dog", 1,
        "llama", 0,
        "iguana", -1
    );
    

    With larger maps, this alternative syntax may be less error-prone:

    Map map = Map.ofEntries(
        Map.entry("cat", 2),
        Map.entry("dog", 1),
        Map.entry("llama", 0),
        Map.entry("iguana", -1)
    );
    

    (This is especially nice if Map.entry is statically imported instead of being referenced explicitly).

    Besides only working with Java 9+, these new approaches are not quite equivalent to the previous one:

    • They don't allow you to specify what Map implementation is used
    • They only create immutable maps
    • They don't create an anonymous subclass of Map

    However, these differences shouldn't matter for many use cases, making this a good default approach for newer versions of Java.

提交回复
热议问题