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?
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.
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