本文介绍了如何直接初始化 HashMap(以字面方式)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 有什么方法可以像这样初始化 Java HashMap 吗?:Is there some way of initializing a Java HashMap like this?: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.推荐答案所有版本如果您碰巧只需要一个条目:有 Collections.singletonMap("key", "value").是的,现在可以了.在 Java 9 中添加了几个工厂方法来简化映射的创建:Yes, this is possible now. In Java 9 a couple of factory methods have been added that simplify the creation of maps :// this works for up to 10 elements:Map<String, String> test1 = Map.of( "a", "b", "c", "d");// this works for any number of elements:import static java.util.Map.entry;Map<String, String> test2 = Map.ofEntries( entry("a", "b"), entry("c", "d"));在上面的例子中,test 和 test2 都是一样的,只是表达 Map 的方式不同.Map.of 方法为地图中最多 10 个元素定义,而 Map.ofEntries 方法没有这样的限制.In the example above both test and test2 will be the same, just with different ways of expressing the 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.请注意,在这种情况下,生成的地图将是一个不可变的地图.如果您希望地图是可变的,您可以再次复制它,例如使用 mutableMap = new HashMap(Map.of("a", "b"));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, e.g. using mutableMap = new HashMap<>(Map.of("a", "b"));(另见 JEP 269 和 Javadoc)不,您必须手动添加所有元素.您可以在匿名子类中使用初始化程序来缩短语法: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:它会生成一个额外的类,这会增加内存消耗、磁盘空间消耗和启动时间在非静态方法的情况下:它持有对创建方法被调用的对象的引用.这意味着当创建的映射对象仍然被引用时,外部类的对象不能被垃圾回收,从而阻塞额外的内存使用函数进行初始化还可以让您在初始化程序中生成地图,但可以避免令人讨厌的副作用: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;} 这篇关于如何直接初始化 HashMap(以字面方式)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-22 15:33