在java中以Enum方式将整数值存储为常量

2022-01-23 00:00:00 enums constants java

我目前正在以下列方式创建整数常量.

I'm currently creating integer constants in the following manner.

public class Constants {
    public static int SIGN_CREATE=0;
    public static int SIGN_CREATE=1;
    public static int HOME_SCREEN=2;
    public static int REGISTER_SCREEN=3;
}

当我尝试以枚举方式执行此操作时

When i try to do this in enum manner

public enum PAGE{SIGN_CREATE,SIGN_CREATE,HOME_SCREEN,REGISTER_SCREEN}

当我使用 PAGE.SIGN_CREATE 它应该返回 1;

and When i used PAGE.SIGN_CREATE it should return 1;

推荐答案

好吧,你不能那样做.PAGE.SIGN_CREATE 永远不会返回 1;它将返回 PAGE.SIGN_CREATE.这就是枚举类型的意义所在.

Well, you can't quite do it that way. PAGE.SIGN_CREATE will never return 1; it will return PAGE.SIGN_CREATE. That's the point of enumerated types.

但是,如果您愿意添加一些击键,您可以向枚举添加字段,如下所示:

However, if you're willing to add a few keystrokes, you can add fields to your enums, like this:


    public enum PAGE{
        SIGN_CREATE(0),
        SIGN_CREATE_BONUS(1),
        HOME_SCREEN(2),
        REGISTER_SCREEN(3);

        private final int value;

        PAGE(final int newValue) {
            value = newValue;
        }

        public int getValue() { return value; }
    }

然后你调用 PAGE.SIGN_CREATE.getValue() 得到 0.

And then you call PAGE.SIGN_CREATE.getValue() to get 0.

相关文章