I have a Java class which has to be generated only once for all the objects that I have - it is a small program. This singleton class holds a mapping of characters. I Googled stack overflow and found that using enum is the most safest way to create a singleton class as Josh Bloch explained in his Java book.
I also read some reviews that singletons are not good. But for my scope I think I need one. So my code is:
public enum SingletonClassA {
INSTANCE;
private static Map<Character, Character> instance;
static {
Map<Character, Character> aCharMap = new HashMap();
aCharMap.put('a', 'e');
aCharMap.put('o', 'u');
// in order to keep short I erased other puts.
instance = Collections.unmodifiableMap(aCharMap);
}
public static Map<Character, Character> getInstance() {
return instance;
}
}
And in order to reach the elements of this HashMap
I use
SingletonClassA.INSTANCE.getInstance().containsKey(aLetter);
Am I creating this singleton class correctly? Do I also need to create a private constructor?
If you have any suggestions about using another data structure for this case please recommend it, write the reasons also.
counter
used for? Is this just supposed to be astatic
, read-onlyMap
? Can you elaborate more on how theMap
is being used and called, say inside some methods of your codebase? \$\endgroup\$