Complex Constants in Java

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 :

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



One Response to “Complex Constants in Java”  

  1. 1 Felix

    Making an object final doesn’t mean you can’t modify it. You just can’t assign a different object to a final variable. So the keys and values in your example are not constant, because you can change the HashMap as you like…

    My solution would be to create a Proxy object for HashMap or whatever you use and make it read-only…

    And why are you using ArrayList if you dont want to add items to the list? A simple array would do (new String[]{ “value1”, “value2” ...})

Leave a Reply