Sunday, August 15, 2010

Initialize static List and Map

If you intend to create a List or Map for your constants, here's how you do it.

List

public static String CONSTANT_1 = "1";
public static String CONSTANT_2 = "2";

public static List CONSTANTS = new ArrayList() { {
add(CONSTANT_1);
add(CONSTANT_2);
}};


Map


public static Map CONSTANTS = new HashMap() { {
put("key1", "value1");
put("key2", "value2");
}};


Even better is to wrap the ArrayList/HashMap by passing them to Collections.unmodifiableList or Collections.unmodifiableMap. Thus making sure that it is truly a constant list/map.

No comments: