新闻资讯

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻资讯列表

java静态map初始化的有哪些方法,java map默认值

发布时间:2023-10-12 17:06:13

java静态map初始化的有哪些方法

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

  1. 使用静态代码块:
public class MyClass {
private static Map map;
static {
map = new HashMap<>();
map.put(1, "One");
map.put(2, "Two");
map.put(3, "Three");
}
}
  1. 使用静态方法:
public class MyClass {
private static Map map = initMap();
private static Map initMap() {
Map map = new HashMap<>();
map.put(1, "One");
map.put(2, "Two");
map.put(3, "Three");
return map;
}
}