扫描二维码下载沐宇APP

沐宇

微信扫码使用沐宇小程序

沐宇

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

扬州沐宇科技
2023-10-12 17:06:13
Java

在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;
}
}

扫码添加客服微信