Linux 拨号vps windows公众号手机端

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

lewis 7年前 (2018-01-21) 阅读数 10 #程序编程
文章标签 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;
}
}
版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门