Java: can I use two different names in an enumeration to count the same thing?

I have an enumeration course with main directions (North, East, South, West):

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

Is there any way to use multiple names of the same thing? For example:

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

In fact, what I want is to be able to sign variables of N or North, and the two operations are exactly the same

Example:

Direction direction1=new Direction.NORTH;
Direction direction2=new Direction.N;
//direction1==direction2

Solution

public enum Direction {
public enum Direction {
  NORTH,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" cannot be used with the automatically generated valueof method Direction Valueof ("n") will throw an illegalargumentexception instead of returning direction NORTH.

You can't write case n: You must use the full name in a switch whose value is direction

In addition, abbreviations should work as well as the full version You can use direction. In enumsets N. Compare it to direction N == Direction. North, get its name () (i.e. "North") and import static yourpackage Direction. N et al

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>