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!
No, a private constructor is not what you want. A constructor initializes an instance of your class (when you call new MyClass()
) , but static state does not belong to an instance and so shouldn't be initialized from the constructor. Initialization that you want to happen when the class is first loaded should be in a static
block placed at the class level.
static {
populateMyMap();
}
But you should never be using static (global) state. Static state makes your system prohibitively difficult to test, it is more nuanced than instance state (for example, you have one copy per load of the class) and it is typically harder to make thread safe.
Consider making your map an instance member of your class instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With