Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
592 views
in Technique[技术] by (71.8m points)

java - 如何直接初始化HashMap(以字面方式)? [重复](How to directly initialize a HashMap (in a literal way)? [duplicate])

This question already has an answer here: (这个问题已经在这里有了答案:)

Is there some way of initializing a Java HashMap like this?: (有没有办法像这样初始化Java HashMap?)

Map<String,String> test = 
    new HashMap<String, String>{"test":"test","test":"test"};

What would be the correct syntax? (正确的语法是什么?) I have not found anything regarding this. (我还没有发现任何有关此的信息。) Is this possible? (这可能吗?) I am looking for the shortest/fastest way to put some "final/static" values in a map that never change and are known in advance when creating the Map. (我正在寻找在地图中放置一些“最终/静态”值的最短/最快方法,这些值永远不会改变,并且在创建地图时会事先知道。)

  ask by jens translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For Java Version 9 or higher: (对于Java版本9或更高版本:)

Yes, this is possible now. (是的,现在有可能。) In Java 9 a couple of factory methods have been added that simplify the creation of maps : (在Java 9中,添加了一些工厂方法,这些方法可简化地图的创建:)

// this works for up to 10 elements:
Map<String, String> test1 = Map.of(
    "a", "b",
    "c", "d"
);

// this works for any number of elements:
Map<String, String> test2 = Map.ofEntries(
    entry("a", "b"),
    entry("c", "d")
);

In the example above both test and test2 will be the same, just with different ways of expressing the Map. (在上面的示例中, testtest2都是相同的,只是表达Map的方式不同。) The Map.of method is defined for up to ten elements in the map, while the Map.ofEntries method will have no such limit. (Map.of方法最多可为地图中的十个元素定义,而Map.ofEntries方法将没有此限制。)

Note that in this case the resulting map will be an immutable map. (请注意,在这种情况下,生成的地图将是不可变的地图。) If you want the map to be mutable, you could copy it again, eg using mutableMap = new HashMap<>(Map.of("a", "b")); (如果您希望地图可变,则可以再次复制它,例如,使用mutableMap = new HashMap<>(Map.of("a", "b"));)

(See also JEP 269 and the Javadoc ) ((另请参见JEP 269Javadoc ))

For up to Java Version 8: (对于Java版本8:)

No, you will have to add all the elements manually. (不,您将必须手动添加所有元素。) You can use an initializer in an anonymous subclass to make the syntax a little bit shorter: (您可以在匿名子类中使用初始化程序,以使语法短一些:)

Map<String, String> myMap = new HashMap<String, String>() {{
        put("a", "b");
        put("c", "d");
    }};

However, the anonymous subclass might introduce unwanted behavior in some cases. (但是,在某些情况下,匿名子类可能会引入不需要的行为。) This includes for example: (例如,这包括:)

  • It generates an additional class which increases memory consumption, disk space consumption and startup-time (它会生成一个附加类,从而增加内存消耗,磁盘空间消耗和启动时间)
  • In case of a non-static method: It holds a reference to the object the creating method was called upon. (对于非静态方法:它包含对创建方法所调用的对象的引用。) That means the object of the outer class cannot be garbage collected while the created map object is still referenced, thus blocking additional memory (这意味着在仍然引用创建的map对象的同时,无法对外部类的对象进行垃圾回收,从而阻塞了额外的内存)

Using a function for initialization will also enable you to generate a map in an initializer, but avoids nasty side-effects: (使用函数进行初始化还将使您能够在初始化器中生成映射,但避免了讨厌的副作用:)

Map<String, String> myMap = createMap();

private static Map<String, String> createMap() {
    Map<String,String> myMap = new HashMap<String,String>();
    myMap.put("a", "b");
    myMap.put("c", "d");
    return myMap;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...