在Java中,靜態Map可以通過靜態代碼塊或靜態方法進行初始化。
public class MyClass {
private static Map<Integer, String> map;
static {
map = new HashMap<>();
map.put(1, "One");
map.put(2, "Two");
map.put(3, "Three");
}
}
public class MyClass {
private static Map<Integer, String> map = initMap();
private static Map<Integer, String> initMap() {
Map<Integer, String> map = new HashMap<>();
map.put(1, "One");
map.put(2, "Two");
map.put(3, "Three");
return map;
}
}