Java 9之前
Java 9之前需要在static块里初始化静态Map。
public class Demo{
private static final Map<Integer, String> myMap;
static {
Map<Integer, String> aMap = new HashMap<>();
aMap.put(1, "one");
aMap.put(2, "two");
myMap = Collections.unmodifiableMap(aMap);
}
}
Java 9
Java 9的Map提供了of()工厂方法用来获取不可更改的Map
private static final Map<Integer, String> myMap = Map.of(1, "one", 2, "two");