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);
}
}

Or

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
}

.



Relevant Pages

  • Re: Queue of function calls
    ... I used a string to represent the argument ... integer arguments, "fs" meant float and string, ecc... ... you can hold everything in a map: ...
    (comp.lang.cpp)
  • Enum dictionary issue: will this work?
    ... The enum constants should get added to a private map with a public, unmodifiable view as they are created. ... Thing (String name) { ...
    (comp.lang.java.programmer)
  • Re: Continually-running Applet has memory leaks - how do I plug them?
    ... same character and copying the whole string on every replace. ... * Add entity value to the map. ... * Expand known entities in an xml string. ... private static final Map standardEntities = new HashMap; ...
    (comp.lang.java.programmer)
  • Re: Continually-running Applet has memory leaks - how do I plug them?
    ... same character and copying the whole string on every replace. ... * Add entity value to the map. ... * Expand known entities in an xml string. ... private static final Map standardEntities = new HashMap; ...
    (comp.lang.java.help)
  • Re: Building up to Epic
    ... there exists a map, the accompanying Act of Parliament and a report from 3 Commissioners about inclosing the village. ... On the map is a footpath which begins from the end of a private road, ends on a private farm and is claimed to be public. ... Newton appointed one of the Wakes -- that private estate the footpath goes into -- as a member of the RS. ... The papers get mixed, I have to shuffle them, try to get them in order while more and more facts swirl around my head. ...
    (rec.arts.sf.composition)