Java Enum Methods - return opposite direction enum Java Enum Methods - return opposite direction enum java java

Java Enum Methods - return opposite direction enum


For those lured here by title: yes, you can define your own methods in your enum. If you are wondering how to invoke such non-static method, you do it same way as with any other non-static method - you invoke it on instance of type which defines or inherits that method. In case of enums such instances are simply ENUM_CONSTANTs.

So all you need is EnumType.ENUM_CONSTANT.methodName(arguments).


Now lets go back to problem from question. One of solutions could be

public enum Direction {    NORTH, SOUTH, EAST, WEST;    private Direction opposite;    static {        NORTH.opposite = SOUTH;        SOUTH.opposite = NORTH;        EAST.opposite = WEST;        WEST.opposite = EAST;    }    public Direction getOppositeDirection() {        return opposite;    }}

Now Direction.NORTH.getOppositeDirection() will return Direction.SOUTH.


Here is little more "hacky" way to illustrate @jedwards comment but it doesn't feel as flexible as first approach since adding more fields or changing their order will break our code.

public enum Direction {    NORTH, EAST, SOUTH, WEST;    // cached values to avoid recreating such array each time method is called    private static final Direction[] VALUES = values();    public Direction getOppositeDirection() {        return VALUES[(ordinal() + 2) % 4];     }}


For a small enum like this, I find the most readable solution to be:

public enum Direction {    NORTH {        @Override        public Direction getOppositeDirection() {            return SOUTH;        }    },     SOUTH {        @Override        public Direction getOppositeDirection() {            return NORTH;        }    },    EAST {        @Override        public Direction getOppositeDirection() {            return WEST;        }    },    WEST {        @Override        public Direction getOppositeDirection() {            return EAST;        }    };    public abstract Direction getOppositeDirection();}


This works:

public enum Direction {    NORTH, SOUTH, EAST, WEST;    public Direction oppose() {        switch(this) {            case NORTH: return SOUTH;            case SOUTH: return NORTH;            case EAST:  return WEST;            case WEST:  return EAST;        }        throw new RuntimeException("Case not implemented");    }}