Skip to content

Instantly share code, notes, and snippets.

@soren
Created May 28, 2014 08:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save soren/c07f6a22daca5c13aca8 to your computer and use it in GitHub Desktop.
Save soren/c07f6a22daca5c13aca8 to your computer and use it in GitHub Desktop.
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
// There's more than one way to do it
public class StaticInitialization {
private static final Map<String, String> MAP_ONE = new HashMap<String, String>() {{
put("one", "1. first");
}};
private static final Map<String, String> MAP_TWO = new HashMap<String, String>();
private static final Map<String, String> MAP_THREE;
private static final Map<String, String> MAP_FOUR;
private static final Map<String, String> MAP_FIVE = createMapFive();
static {
// Initialize MAP_TWO
MAP_TWO.put("one", "2. first");
MAP_TWO.put("two", "2. second");
// Initialize MAP_THREE
Map<String, String> map = new HashMap<String, String>();
map.put("one", "3. first");
map.put("two", "3. second");
map.put("three", "3. third");
MAP_THREE = Collections.unmodifiableMap(map);
// Initialize MAP_FOUR
MAP_FOUR = Collections.unmodifiableMap(new HashMap<String, String>() {{
put("one", "4. first");
put("two", "4. second");
put("three", "4. third");
put("four", "4. fourth");
}});
}
private static Map<String, String> createMapFive() {
return Collections.unmodifiableMap(new HashMap<String, String>() {{
put("one", "5. first");
put("two", "5. second");
put("three", "5. third");
put("four", "5. fourth");
put("five", "5. fifth");
}});
}
public static void main(String[] args) {
System.out.println(MAP_ONE.get("one"));
System.out.println(MAP_TWO.get("two"));
System.out.println(MAP_THREE.get("three"));
System.out.println(MAP_FOUR.get("four"));
System.out.println(MAP_FIVE.get("five"));
System.out.println("---------");
MAP_ONE.put("one", "1) First");
MAP_TWO.put("two", "2) Second");
try { MAP_THREE.put("three", "3) Third"); } catch (Exception e) { }
try { MAP_FOUR.put("four", "4) Fourth"); } catch (Exception e) { }
try { MAP_FIVE.put("five", "5) Fifth"); } catch (Exception e) { }
System.out.println(MAP_ONE.get("one"));
System.out.println(MAP_TWO.get("two"));
System.out.println(MAP_THREE.get("three"));
System.out.println(MAP_FOUR.get("four"));
System.out.println(MAP_FIVE.get("five"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment