简体   繁体   English

用于在Java中初始化散列映射的良好设计模式选择

[英]Good design pattern choice for initializing a hashmap in Java

I have a non-static class in Java that has a static hashmap field. 我在Java中有一个非静态类,它有一个静态hashmap字段。 The hashmap should be initialized with some key-value pairs generated by code. 应使用代码生成的一些键值对初始化hashmap。 The hashmap is not to be changed after that. 之后不会更改hashmap。

How should this be achieved? 应该如何实现? Should I just create a static init method and make sure to run this once before using the class, or are there better ways of doing it? 我应该创建一个静态init方法,并确保在使用该类之前运行一次,或者有更好的方法吗?

You can use a static initializer block in your class. 您可以在类中使用静态初始化程序块。

eg 例如

private static Map<String, String> myMap;
static {
    HashMap<String,String> map = new HashMap<String,String>();
    map.put("foo","bar");

    myMap = Collections.unmodifiableMap(map);
}

You can easily create immutable maps with Google Guava library: 您可以使用Google Guava库轻松创建不可变地图:

private static Map<String, String> map = ImmutableMap.of(
    "key1", "value1",
    "key2", "value2");

If you want to use it for many values then builder() is provided. 如果要将它用于许多值,则提供builder()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM