Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static HashMap Initialization

I have this class, I want to know:
1° Is this the best way to define a static HashMasp
2° Is this the best way to do it in a Spring based app?(does Spring offer a better way to do this?)

Thanks in advance!

    public class MyHashMap {
        private static final Map<Integer, String> myMap;
        static {
            Map<CustomEnum, String> aMap = new HashMap<CustomEnum, String>();
            aMap.put(CustomEnum.UN, "one");
            aMap.put(CustomEnum.DEUX, "two");
            myMap = Collections.unmodifiableMap(aMap);
        }

        public static String getValue(CustomEnum id){
            return myMap.get(id);
        }
    }


    System.out.println(MyHashMap.getValue(CustomEnum.UN));
like image 768
Marco Aviles Avatar asked Sep 03 '25 01:09

Marco Aviles


1 Answers

There are a few approaches to doing this. For example if your map is immutable you could consider using the Google Guava libraries It has an ImmutableMap class which could be used to construct your map as:-

static final ImmutableMap<String, Integer> WORD_TO_INT =
       new ImmutableMap.Builder<String, Integer>()
           .put("one", 1)
           .put("two", 2)
           .put("three", 3)
           .build();

If you are already using the Spring Framework and wiring your beans using XML, then you could fill the map in directly via the XML as :-

    ...    
<!-- creates a java.util.Map instance with the supplied key-value pairs -->
<util:map id="emails">
    <entry key="pechorin" value="[email protected]"/>
    <entry key="raskolnikov" value="[email protected]"/>
    <entry key="stavrogin" value="[email protected]"/>
    <entry key="porfiry" value="[email protected]"/>
</util:map>
    ...
like image 172
Stephen84s Avatar answered Sep 04 '25 23:09

Stephen84s