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
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 switch
es 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 EnumSet
s, compare it for equality Direction.N == Direction.NORTH
, get its name()
(which is "NORTH"
), import static yourpackage.Direction.N;
, etc.
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.
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