When using flags in Java, I have seen two main approaches. One uses int values and a line of if-else statements. The other is to use enums and case-switch statements. I was wondering if there was a difference in terms of memory usage and speed between using enums vs ints for flags? Both ints and enums can use both switch or if-then-else, and memory usage is also minimal for both, and speed is similar - there's no significant difference between them on the points you raised. However, the most important difference is the type checking. Enums are checked, ints are not. Consider this code:
public class SomeClass {
public static int RED = 1;
public static int BLUE = 2;
public static int YELLOW = 3;
public static int GREEN = 3; // sic
private int color;
public void setColor(int color) {
this.color = color;
}
}
While many clients will use this properly,
new SomeClass().setColor(SomeClass.RED);
There is nothing stopping them from writing this:
new SomeClass().setColor(999);
There are three main problems with using the
public static final
pattern:
- The problem occurs at runtime, not compile time, so it's going to be more expensive to fix, and harder to find the cause
- You have to write code to handle bad input - typically a
if-then-else
with a final else throw new IllegalArgumentException("Unknown color " + color);
- again expensive - There is nothing preventing a collision of constants - the above class code will compile even though
YELLOW
and GREEN
both have the same value 3
If you use
enums
, you address all these problems:
- Your code won't compile unless you pass valid values in
- No need for any special "bad input" code - the compiler handles that for you
- Enum values are unique
由此可见使用枚举代替int不仅可以减少代码的编写还能减少错误的产生! Found here:http://stackoverflow.com/questions/9254637/java-enum-vs-int