第一种方法:static块初始化
public class Demo{ private static final Map<String, String> myMap; static { myMap = new HashMap<String, String>(); myMap.put("a", "b"); myMap.put("c", "d"); } }
第二种方法:双括号初始化 (匿名内部类)
HashMap<String, String > h = new HashMap<String, String>(){{ put("a","b"); }};
时间: 2024-10-09 14:42:09