Re: constructing a constant HashMap

On 10/15/11 6:14 PM, Roedy Green wrote:
What is your preferred way of building a HashMap when all the values
are known at compile time?

public class StaticHash {
private static final Map<String, String> map;

static {
Map<String, String> mutableMap = new HashMap<String,String>();
mutableMap.put("First Key", "First Value");
mutableMap.put("Second Key", "Second Value");
mutableMap.put("Third Key", "Third Value");
map = Collections.unmodifiableMap(mutableMap);


enum MyKeys {
FIRST("First Value"),
SECOND("Second Value"),
THIRD("Third Value")
private final String value;
private MyKeys(String value) { this.value = value; }
//... if you need a reverse look-up, static initializer (as above)
// that builds the reverse look-up map