Search code examples
javaconstructorhashmapstatic-constructor

Constructor in a class of static methods


I've got a class of static methods that can be performed on a map held within the class, and I want the map to be set up when the class is called. I've tried using a private contructor, but it isn't being called. The relevant parts of my code are:

public class MyClass
{
    private static final String KEYS = "ABC";
    private static final String[] DATA = {"AAA", "BBB", "CCC"};
    private static HashMap<Character, String> myMap;

    private MyClass() {
        System.out.println("Running constructor");
        populateMyMap();
    }

    private static void populateMyMap() {
        myMap = new HashMap<Character, String>();
        for (int i=0; i < KEYS.length; i++) {
            myMap.put(KEYS.charAt(i), DATA[i]);
        }
    }

    //various static methods
}

Is a private constructor the right thing to be using here, and if so what am I doing wrong?

Sorry if this is a duplicate; I've tried searching for answers, but I'm not sure what to search for!


Solution

  • The static initializer block has been mentioned in several other answers. But practically I find the following idiom more frequently in the wild:

    public class MyClass
    {
        private static HashMap<Character, String> myMap = createMyMap();
    
        private static HashMap<Character, String> createMyMap() {
            HashMap<Character, String> myTmpMap = new HashMap<Character, String>();
            for (int i=0; i < KEYS.length; i++) {
                myTmpMap.put(KEYS.charAt(i), DATA[i]);
            }
            return myTmpMap;
        }
    }