简体   繁体   中英

Good design pattern choice for initializing a hashmap in Java

I have a non-static class in Java that has a static hashmap field. The hashmap should be initialized with some key-value pairs generated by code. The hashmap is not to be changed after that.

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?

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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