Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EnumMap vs. Enum values

Tags:

java

enums

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?

like image 464
Eva Avatar asked Jun 30 '12 15:06

Eva


1 Answers

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.

like image 147
Marko Topolnik Avatar answered Nov 08 '22 06:11

Marko Topolnik