P
peter
What's the additional value of 'EnumMap' ?
I'm asking this, because it seems to me that the same
result can be accomplished by using a plain 'HashMap' (?).
See these two examples :
******
Example 01 (with 'EnumMap') :
public enum TrafficLightColor { red, orange, green };
public void getInstruction()
{
EnumMap<TrafficLightColor, String> instructions =
new EnumMap<TrafficLightColor, String>(TrafficLightColor.class);
instructions.put(TrafficLightColor.red, "Stop");
instructions.put(TrafficLightColor.orange, "Slow down or accelerate");
instructions.put(TrafficLightColor.green, "Drive");
TrafficLightColor k = TrafficLightColor.red;
System.out.printf("The instruction for color %s is : '%s'.", k, instructions.get(k));
}
******
Example 02 (with 'HashMap') :
public enum TrafficLightColor { red, orange, green };
public void getInstruction()
{
HashMap<TrafficLightColor, String> instructions =
new HashMap<TrafficLightColor, String>();
instructions.put(TrafficLightColor.red, "Stop");
instructions.put(TrafficLightColor.orange, "Slow down or accelerate");
instructions.put(TrafficLightColor.green, "Drive");
TrafficLightColor k = TrafficLightColor.red;
System.out.printf("The instruction for color %s is : '%s'.", k, instructions.get(k));
}
******
The outcome is the same, so what's the big difference ?
Why (or when) would one prefer to use 'EnumMap'
in favor to 'HashMap' ?
I'm asking this, because it seems to me that the same
result can be accomplished by using a plain 'HashMap' (?).
See these two examples :
******
Example 01 (with 'EnumMap') :
public enum TrafficLightColor { red, orange, green };
public void getInstruction()
{
EnumMap<TrafficLightColor, String> instructions =
new EnumMap<TrafficLightColor, String>(TrafficLightColor.class);
instructions.put(TrafficLightColor.red, "Stop");
instructions.put(TrafficLightColor.orange, "Slow down or accelerate");
instructions.put(TrafficLightColor.green, "Drive");
TrafficLightColor k = TrafficLightColor.red;
System.out.printf("The instruction for color %s is : '%s'.", k, instructions.get(k));
}
******
Example 02 (with 'HashMap') :
public enum TrafficLightColor { red, orange, green };
public void getInstruction()
{
HashMap<TrafficLightColor, String> instructions =
new HashMap<TrafficLightColor, String>();
instructions.put(TrafficLightColor.red, "Stop");
instructions.put(TrafficLightColor.orange, "Slow down or accelerate");
instructions.put(TrafficLightColor.green, "Drive");
TrafficLightColor k = TrafficLightColor.red;
System.out.printf("The instruction for color %s is : '%s'.", k, instructions.get(k));
}
******
The outcome is the same, so what's the big difference ?
Why (or when) would one prefer to use 'EnumMap'
in favor to 'HashMap' ?