在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;
}
}
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读: Java中怎么安全的进行SQL拼接