Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Can I use two different names in an enum to count as the same thing?

I have an enum class with the cardinal directions(North, East, South, West):

public enum Direction {
    NORTH,
    EAST,
    SOUTH,
    WEST;
}

Is there a way to be able to use multiple names for the same thing? For example something like this:

public enum Direction {
    NORTH or N,
    EAST or E,
    SOUTH or S,
    WEST or W;
}

In practice what I want is to be able and sign to a variable either N or NORTH and have the two operations be exactly the same.

Example:

Direction direction1=new Direction.NORTH;
Direction direction2=new Direction.N;
//direction1==direction2
like image 878
Pithikos Avatar asked May 10 '11 22:05

Pithikos


2 Answers

public enum Direction {
  NORTH,
  EAST,
  SOUTH,
  WEST,
  ;

  // Convenience names.
  public static final Direction N = NORTH;
  public static final Direction E = EAST;
  public static final Direction S = SOUTH;
  public static final Direction W = WEST;
}

is legal, but "N" will not work with the auto-generated valueOf method. I.e. Direction.valueOf("N") will throw an IllegalArgumentException instead of returning Direction.NORTH.

You also cannot write case N:. You have to use the full names in switches whose value is a Direction.

Other than that, the abbreviated form should work just as well as the full version. You can use Direction.N in EnumSets, compare it for equality Direction.N == Direction.NORTH, get its name() (which is "NORTH"), import static yourpackage.Direction.N;, etc.

like image 132
Mike Samuel Avatar answered Oct 03 '22 03:10

Mike Samuel


You could do something like this (East and West omitted).

public enum Direction {
    NORTH {
        @Override
        Direction getDirection() {
            return NORTH;
        }
    },
    N {
        @Override
        Direction getDirection() {
            return NORTH;
        }
    },
    SOUTH {
        @Override
        Direction getDirection() {
            return SOUTH;
        }
    },
    S {
        @Override
        Direction getDirection() {
            return SOUTH;
        }
    }   ;

    abstract Direction getDirection();
}

Then you could something like this

public void foo(Direction arg) {
  Direction d = arg.getDirection();
}

Then you will always be dealing with only NORTH, SOUTH, EAST, and WEST.

like image 22
JustinKSU Avatar answered Oct 03 '22 04:10

JustinKSU