Reputation: 4700
What's the difference between this:
public enum Direction {
NORTH(90),
EAST(0),
SOUTH(270),
WEST(180);
private final int degree_;
private Direction(int degree) {
degree_ = degree;
}
public int getDegree() {
return degree_;
}
public static void main(String[] args) {
System.out.println(NORTH.getDegree());
}
}
and this:
public enum Direction {
NORTH,
EAST,
SOUTH,
WEST;
public static void main(String[] args) {
EnumMap<Direction, int> directionToDegree = new EnumMap<Direction, int>(Direction.class);
directionToDegree.put(NORTH, 90);
directionToDegree.put(EAST, 0);
directionToDegree.put(SOUTH, 270);
directionToDegree.put(WEST, 180);
System.out.println(directionToDegree.get(NORTH));
}
}
Is one easier to read? Is one more flexible? Is one used more conventionally? Does one run faster? Any other pros and cons?
Upvotes: 8
Views: 3613
Reputation: 23903
The first case you have a property bonded to the enum
value (just one value).
The second one you have the value associate to the enum managed outside.
Imagine now in your application you wanna access this values. If this is constant on the second case it would be much more complicated to refer the map from everywhere.
The second approach would be useful when you have different contexts. For instance: NORTH
, in a specific context NORTH
should be 90, but in another context it would be required another value associated to it (a context here could be a specific implementation).
Upvotes: 9
Reputation: 200168
The main use case for the EnumMap
is when you want to attach additional data to an enum
you don't own. Typically you are using a public library that has an enum and you need to annotate each member with your data.
As a general rule, whenever both approaches are available to you, use the first one.
Upvotes: 10
Reputation: 15778
Adding values to the enum constants themselves makes them usable without a reference to another object. If you store this information in a map, you have to pass references to the map around. If these are fundamental properties of the notions the constants represent, it's probably best to add the values to the constants themselves instead of storing them in a map.
Using values on the enum constants will be faster than storing them in a map.
Upvotes: 7