Android 下枚举型使用、及与 int 转换的困惑解答
扫描二维码
随时随地手机看文章
在 C/C++ 环境下,已经习惯使用枚举型常量,但在 Android 下使用时发现枚举与 C/C++ 下是完全不同的。
Android 下,枚举其实是类。
使用感觉困难,主要是枚举与 int 之间的转换。如果枚举的定义如下 weekday 所示,还可以通过 ordinal() 和 values()[] 方法进行转换。
但不幸的是,我使用的是如下 weekday_2 所示的枚举类型,我是没有找到对应的转换方法。
最后没有办法,将枚举修改为一般的常量定义,如下:
public static final short MAX_BUFFER_SIZE = 2048;
public class Test {
public enum weekday
{
sun,
mou,
tue,
thu,
fri,
sat,
wed,
};
public enum weekday_2
{
sun(0x1),
mou(0x2),
tue(0x3),
thu(0x4),
fri(0x5),
sat(0x6),
wed(0x7),
large(0x99); // 如果增加此值,通过 ordinal() 方法得到的值是多少?
private int iSet;
weekday_2(int iValue) {
this.iSet = iValue;
}
public int Get() {
return this.iSet;
}
};
}
对于上面两个枚举定义 weekday 和 weekday_2:
int x = weekday.sun.ordinal(); weekday sun = weekday.values()[x];
与
int x = weekday_2.sun.ordinal(); weekday_2 sun = weekday_2.values()[x];
有什么差别?除了 weekday_2 中的 large 成员外,其它成员的值是否相同?
void TestEnumValue() {
TstEnum.weekday day = TstEnum.weekday.sun;
TstEnum.weekday_2 day2 = TstEnum.weekday_2.sun;
TstEnum.weekday_2 day2_large = TstEnum.weekday_2.large;
int iDay = day.ordinal();
int iDay2 = day2.ordinal();
int iDay2Large = day2_large.ordinal();
System.out.println("Enum Test" + "value of sun : " + Integer.toString(iDay) + "/" + Integer.toString(iDay2)
+ ". Large: " + Integer.toString(iDay2Large));
}
执行后输出的结果是: Enum Testvalue of sun : 0/0. Large: 7
weekday_2 的成员 sun 并未输出其真实的数值,而是输出了下标。
对应之,weekday.values()[x]; 也是下标。若知道 weekday_2 的一个变量值是: 整型 0x99, 想转成对应的枚举。如果使用 weekday.values()[0x99] 则会直接越界。
(1) 执行:javac Test.java
编译没有出错即可。
(2) 执行: javap Test
得到以下的输出:
Compiled from "Test.java"
public class Test {
int x;
Test$weekday sun;
public Test();
}
(3) 执行: javap Test$weekday
得到以下输出:
Compiled from "Test.java"
public final class Test$weekday extends java.lang.Enum{
public static final Test$weekday sun;
public static final Test$weekday mou;
public static final Test$weekday tue;
public static final Test$weekday thu;
public static final Test$weekday fri;
public static final Test$weekday sat;
public static final Test$weekday wed;
public static Test$weekday[] values();
public static Test$weekday valueOf(java.lang.String);
static {};
}
(4) 执行: javap Test$weekday_2
得到以下输出:
Compiled from "Test.java"
public final class Test$weekday_2 extends java.lang.Enum{
public static final Test$weekday_2 sun;
public static final Test$weekday_2 mou;
public static final Test$weekday_2 tue;
public static final Test$weekday_2 thu;
public static final Test$weekday_2 fri;
public static final Test$weekday_2 sat;
public static final Test$weekday_2 wed;
public static Test$weekday_2[] values();
public static Test$weekday_2 valueOf(java.lang.String);
public int Get();
static {};
}
从以上反编译出来的代码可以得出以下结论:
(1) weekday 和 weekday_2 枚举类是final class,即不能被继承,而它本身是继承于 Enum
(2) 枚举值是 weekday 或 weekday_2 对象,而且是 static final 修饰的





