Yes, it can be a constant. You should declare your HashMap
instance as follows:
class <class name> {
private static final HashMap<Integer, String> tensNumberConversion = new HashMap<>();
static {
tensNumberConversion.put(2, "twenty");
tensNumberConversion.put(3, "thirty");
tensNumberConversion.put(4, "forty");
tensNumberConversion.put(5, "fifty");
tensNumberConversion.put(6, "sixty");
tensNumberConversion.put(7, "seventy");
tensNumberConversion.put(8, "eighty");
tensNumberConversion.put(9, "ninety");
}
}
However, this is only a constant reference. While you can not reassign tensNumberConversion
to something else, you still can change the contents of your map later at runtime:
tensNumberConversion = new HashMap<>(); // won't compile
tensNumberConversion.put(9, "one"); // succeeds
If you want the contents of your map constant too, you should wrap the HashMap
into an unmodifiable map:
class <class name> {
private static final Map<Integer, String> tensNumberConversion = initMap();
private static Map<Integer, String> initMap() {
Map<Integer, String> map = new HashMap<>();
map.put(2, "twenty");
map.put(3, "thirty");
map.put(4, "forty");
map.put(5, "fifty");
map.put(6, "sixty");
map.put(7, "seventy");
map.put(8, "eighty");
map.put(9, "ninety");
return Collections.unmodifiableMap(map);
}
}