如果我在 getByIntValue()
中使用 switch
会怎样?真的有必要使用 SparseArray
吗?
public enum Gender {
Unknown(0),
Male(1),
Female(2);
private static final SparseArray<Gender> lookupTable = new SparseArray<Gender>();
static {
for (final Gender gender : EnumSet.allOf(Gender.class)) {
lookupTable.put(gender.intValue, gender);
}
}
private final int intValue;
public static Gender getByIntValue(int val) {
return lookupTable.get(val);
}
private Gender(int intValue) {
this.intValue = intValue;
}
public int getIntValue() {
return intValue;
}
}
最佳答案
由于您的 int 值从 0 到 2,没有漏洞,您确实可以简单地使用数组。开关也可以,尽管它可能比数组查找稍微慢一些。但除非您调用该方法数十亿次,否则不会产生任何明显的差异。使用您认为最清晰、最容易理解和维护的内容。
关于java - 在 Enum 中使用 switch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14519207/