本文翻译自:Cast Int to enum in Java
What is the correct way to cast an Int to an enum in Java given the following enum? 在给定以下枚举的情况下,将Int转换为枚举的正确方法是什么?
public enum MyEnum
{
EnumValue1,
EnumValue2
}
MyEnum enumValue = (MyEnum) x; //Doesn't work???
#1楼
参考:https://stackoom.com/question/OfNo/在Java中将Int转换为枚举
#2楼
A good option is to avoid conversion from int
to enum
: for example, if you need the maximal value, you may compare x.ordinal() to y.ordinal() and return x or y correspondingly. 一个好的选择是避免从int
转换为enum
:例如,如果需要最大值,可以将x.ordinal()与y.ordinal()进行比较,并相应地返回x或y。 (You may need to re-order you values to make such comparison meaningful.) (您可能需要重新排序值以使这种比较有意义。)
If that is not possible, I would store MyEnum.values()
into a static array. 如果那是不可能的,我会将MyEnum.values()
存储到静态数组中。
#3楼
I cache the values and create a simple static access method: 我缓存值并创建一个简单的静态访问方法:
public static enum EnumAttributeType {
ENUM_1,
ENUM_2;
private static EnumAttributeType[] values = null;
public static EnumAttributeType fromInt(int i) {
if(EnumAttributeType.values == null) {
EnumAttributeType.values = EnumAttributeType.values();
}
return EnumAttributeType.values[i];
}
}
#4楼
If you want to give your integer values, you can use a structure like below 如果要提供整数值,可以使用如下结构
public enum A
{
B(0),
C(10),
None(11);
int id;
private A(int i){id = i;}
public int GetID(){return id;}
public boolean IsEmpty(){return this.equals(A.None);}
public boolean Compare(int i){return id == i;}
public static A GetValue(int _id)
{
A[] As = A.values();
for(int i = 0; i < As.length; i++)
{
if(As[i].Compare(_id))
return As[i];
}
return A.None;
}
}
#5楼
This is the same answer as the doctors but it shows how to eliminate the problem with mutable arrays. 这与医生的答案相同,但它显示了如何消除可变阵列的问题。 If you use this kind of approach because of branch prediction first if will have very little to zero effect and whole code only calls mutable array values() function only once. 如果你使用这种方法,因为分支预测首先是否会产生非常小的效果,整个代码只调用一次可变数组值()函数。 As both variables are static they will not consume n * memory for every usage of this enumeration too. 由于两个变量都是静态的,因此每次使用此枚举时也不会消耗n *内存。
private static boolean arrayCreated = false;
private static RFMsgType[] ArrayOfValues;
public static RFMsgType GetMsgTypeFromValue(int MessageID) {
if (arrayCreated == false) {
ArrayOfValues = RFMsgType.values();
}
for (int i = 0; i < ArrayOfValues.length; i++) {
if (ArrayOfValues[i].MessageIDValue == MessageID) {
return ArrayOfValues[i];
}
}
return RFMsgType.UNKNOWN;
}
#6楼
Here's the solution I plan to go with. 这是我计划采用的解决方案。 Not only does this work with non-sequential integers, but it should work with any other data type you may want to use as the underlying id for your enum values. 这不仅适用于非顺序整数,而且它可以与您可能希望用作枚举值的基础id的任何其他数据类型一起使用。
public Enum MyEnum {
THIS(5),
THAT(16),
THE_OTHER(35);
private int id; // Could be other data type besides int
private MyEnum(int id) {
this.id = id;
}
public int getId() {
return this.id;
}
public static Map<Integer, MyEnum> buildMap() {
Map<Integer, MyEnum> map = new HashMap<Integer, MyEnum>();
MyEnum[] values = MyEnum.values();
for (MyEnum value : values) {
map.put(value.getId(), value);
}
return map;
}
}
I only need to convert id's to enums at specific times (when loading data from a file), so there's no reason for me to keep the Map in memory at all times. 我只需要在特定时间将id转换为枚举(从文件加载数据时),因此我没有理由始终将Map保留在内存中。 If you do need the map to be accessible at all times, you can always cache it as a static member of your Enum class. 如果确实需要始终可以访问地图,则可以始终将其缓存为Enum类的静态成员。