java静态map初始化的方法是什么

1192
2023/10/1 17:06:13
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在Java中,静态Map可以通过静态代码块或静态方法进行初始化。

  1. 使用静态代码块:
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");
}
}
  1. 使用静态方法:
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中Thread.sleep(1000)指的是什么意思