EnumMap and Enum Values

What is 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 it easier to read? Is it even more flexible? Is it used more traditionally? Do you run faster? Any other pros and cons?

+6
source share
3 answers

In the first case, you have a property associated with the enum value (just one value).

Second, you have a value associated with a managed external enum.

Imagine that now in your application you want to access these values. If it is constant in the second case, it would be much more difficult to take the card from everywhere.

The second approach would be useful if you have different contexts. For example: NORTH , in a specific context, NORTH should be 90, but in another context, it will need a different value associated with it (the context here may be a specific implementation).

+6
source

The main use EnumMap is when you want to attach additional data to an enum that you are not. As a rule, you use a public library with an enumeration, and you need to comment on each member with your data.

As a rule, when both approaches are available to you, use the first.

+7
source

Adding values ​​to enum constants makes them suitable for use without reference to another object. If you store this information on a map, you need to transfer links to the map. If these are the fundamental properties of concepts that constants represent, then it is probably best to add values ​​to the constants themselves rather than storing them on a map.

Using values ​​in enumeration constants will be faster than saving them on the map.

+6
source

Source: https://habr.com/ru/post/919394/


All Articles