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));
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>
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With