在java中以枚举方式存储整数值作为常量 [英] Storing integer values as constants in Enum manner in java

查看:580
本文介绍了在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。

这篇关于在java中以枚举方式存储整数值作为常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆