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

Storing integer values as constants in Enum manner in java(在java中以Enum方式将整数值存储为常量)

本文介绍了在java中以Enum方式将整数值存储为常量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这篇关于在java中以Enum方式将整数值存储为常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:在java中以Enum方式将整数值存储为常量

基础教程推荐