在Java中,静态Map可以通过静态代码块或静态方法进行初始化。
- 使用静态代码块:
public class MyClass { private static Mapmap; static { map = new HashMap<>(); map.put(1, "One"); map.put(2, "Two"); map.put(3, "Three"); } }
- 使用静态方法:
public class MyClass { private static Mapmap = initMap(); private static Map initMap() { Map map = new HashMap<>(); map.put(1, "One"); map.put(2, "Two"); map.put(3, "Three"); return map; } }