第一种方法:static块初始化
[java] view plain copy
- public class Demo{
- private static final Map<String, String> myMap;
- static
- {
- myMap = new HashMap<String, String>();
- myMap.put("a", "b");
- myMap.put("c", "d");
- }
- }
第二种方法:双括号初始化 (匿名内部类)
[java] view plain copy
- HashMap<String, String > h = new HashMap<String, String>(){{
- put("a","b");
- }};
慎用, 非静态内部类/ 匿名内部类包含了外围实例的引用, 如果拥有比外部类更长的生命周期,有内存泄露隐患
第三种方法:Guava
[java] view plain copy
- Map<String, Integer> left = ImmutableMap.of("a", 1, "b", 2, "c", 3);
- //或者
- Map<String, String> test = ImmutableMap.<String, String>builder()
- .put("k1", "v1")
- .put("k2", "v2")
- ...
- .build();
原文地址:https://www.cnblogs.com/exmyth/p/8110942.html
时间: 2024-10-11 21:08:17