在java中以枚举方式将整数值存储为常量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3990319/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Storing integer values as constants in Enum manner in java
提问by Labeeb Panampullan
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}
and When i used PAGE.SIGN_CREATE
it should return 1;
当我使用PAGE.SIGN_CREATE
它时,它应该返回 1;
采纳答案by BlairHippo
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.
好吧,你不能完全那样做。 PAGE.SIGN_CREATE
永远不会返回 1;它会回来PAGE.SIGN_CREATE
。这就是枚举类型的意义所在。
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; }
}
And then you call PAGE.SIGN_CREATE.getValue()
to get 0.
然后你打电话PAGE.SIGN_CREATE.getValue()
给0。
回答by Adam
You can use ordinal. So PAGE.SIGN_CREATE.ordinal()
returns 1
.
您可以使用序数。所以PAGE.SIGN_CREATE.ordinal()
返回1
。
EDIT:
编辑:
The only problem with doing this is that if you add, remove or reorder the enum values you will break the system. For many this is not an issue as they will not remove enums and will only add additional values to the end. It is also no worse than integer constants which also require you not to renumber them. However it is best to use a system like:
这样做的唯一问题是,如果您添加、删除或重新排序枚举值,您将破坏系统。对于许多人来说,这不是问题,因为他们不会删除枚举,只会在最后添加额外的值。它也不比整数常量差,后者也要求您不要对它们重新编号。但是,最好使用如下系统:
public enum PAGE{
SIGN_CREATE0(0), SIGN_CREATE(1) ,HOME_SCREEN(2), REGISTER_SCREEN(3)
private int id;
PAGE(int id){
this.id = id;
}
public int getID(){
return id;
}
}
You can then use getID
. So PAGE.SIGN_CREATE.getID()
returns 1
.
然后您可以使用getID
. 所以PAGE.SIGN_CREATE.getID()
返回1
。
回答by TJR
You could store that const value in the enum like so. But why even use the const? Are you persisting the enum's?
您可以像这样将 const 值存储在枚举中。但是为什么还要使用const呢?你坚持枚举吗?
public class SO3990319 {
public static enum PAGE {
SIGN_CREATE(1);
private final int constValue;
private PAGE(int constValue) {
this.constValue = constValue;
}
public int constValue() {
return constValue;
}
}
public static void main(String[] args) {
System.out.println("Name: " + PAGE.SIGN_CREATE.name());
System.out.println("Ordinal: " + PAGE.SIGN_CREATE.ordinal());
System.out.println("Const: " + PAGE.SIGN_CREATE.constValue());
System.out.println("Enum: " + PAGE.valueOf("SIGN_CREATE"));
}
}
Edit:
编辑:
It depends on what you're using the int's for whether to use EnumMap or instance field.
这取决于您使用 int 的内容是使用 EnumMap 还是实例字段。
回答by Mark Peters
The most common valid reason for wanting an integer constant associated with each enum value is to interoperate with some other component which still expects those integers (e.g. a serialization protocol which you can't change, or the enums represent columns in a table, etc).
想要一个与每个枚举值关联的整数常量的最常见的有效原因是与其他一些仍然需要这些整数的组件进行互操作(例如,您无法更改的序列化协议,或者枚举表示表中的列等) .
In almost all cases I suggest using an EnumMap
instead. It decouples the components more completely, if that was the concern, or if the enums represent column indices or something similar, you can easily make changes later on (or even at runtime if need be).
在几乎所有情况下,我都建议使用 anEnumMap
代替。它更完全地分离组件,如果这是问题,或者如果枚举代表列索引或类似的东西,您可以稍后轻松进行更改(或者甚至在运行时,如果需要)。
private final EnumMap<Page, Integer> pageIndexes = new EnumMap<Page, Integer>(Page.class);
pageIndexes.put(Page.SIGN_CREATE, 1);
//etc., ...
int createIndex = pageIndexes.get(Page.SIGN_CREATE);
It's typically incredibly efficient, too.
它通常也非常高效。
Adding data like this to the enum instance itself can be very powerful, but is more often than not abused.
将这样的数据添加到枚举实例本身可能非常强大,但经常被滥用。
Edit:Just realized Bloch addressed this in Effective Java / 2nd edition, in Item 33: Use EnumMap
instead of ordinal indexing.
编辑:刚刚意识到 Bloch 在 Effective Java/2nd edition 的Item 33: Use EnumMap
instead of ordinal indexing 中解决了这个问题。
回答by Top-Master
if you want to be able to convert integer
back to corresponding enum
with selected value see Constants.forValue(...)
in below auto generated code but if not the answer of BlairHippois best way to do it.
如果您希望能够转换integer
回enum
与选定值相对应的值,请参见Constants.forValue(...)
下面的自动生成代码,但如果不是,BlairHippo的答案是最好的方法。
public enum Constants
{
SIGN_CREATE(0),
SIGN_CREATE(1),
HOME_SCREEN(2),
REGISTER_SCREEN(3);
public static final int SIZE = java.lang.Integer.SIZE;
private int intValue;
private static java.util.HashMap<Integer, Constants> mappings;
private static java.util.HashMap<Integer, Constants> getMappings()
{
if (mappings == null)
{
synchronized (Constants.class)
{
if (mappings == null)
{
mappings = new java.util.HashMap<Integer, Constants>();
}
}
}
return mappings;
}
private Constants(int value)
{
intValue = value;
getMappings().put(value, this);
}
public int getValue()
{
return intValue;
}
public static Constants forValue(int value)
{
return getMappings().get(value);
}
}
回答by Clayton Bell
I found this to be helpful:
我发现这很有帮助:
http://dan.clarke.name/2011/07/enum-in-java-with-int-conversion/
http://dan.clarke.name/2011/07/enum-in-java-with-int-conversion/
public enum Difficulty
{
EASY(0),
MEDIUM(1),
HARD(2);
/**
* Value for this difficulty
*/
public final int Value;
private Difficulty(int value)
{
Value = value;
}
// Mapping difficulty to difficulty id
private static final Map<Integer, Difficulty> _map = new HashMap<Integer, Difficulty>();
static
{
for (Difficulty difficulty : Difficulty.values())
_map.put(difficulty.Value, difficulty);
}
/**
* Get difficulty from value
* @param value Value
* @return Difficulty
*/
public static Difficulty from(int value)
{
return _map.get(value);
}
}