Dave Perrett

Complex Constants in Java

java, programming, quickie

If you want to assign a complex class (such as a HashMap / ArrayList etc) as a constant in Java, use the static initializer block construct :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import java.util.ArrayList;
import java.util.HashMap;

public class MyConstants {

       public final static HashMap myHashMap = new HashMap();
       static {
    myHashMap.put("key1", "value1");
    myHashMap.put("key2", "value2");
    myHashMap.put("key3", "value3");
  }

       public final static ArrayList myArrayList = new ArrayList();
       static {
    myArrayList.add("value4");
    myArrayList.add("value5");
    myArrayList.add("value6");
  }
}