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
intsandenumscan 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.
Enumsare checked,intsare not.Consider this code:
While many clients will use this properly,
There is nothing stopping them from writing this:
There are three main problems with using the
public static finalpattern:if-then-elsewith a finalelse throw new IllegalArgumentException("Unknown color " + color);– again expensiveYELLOWandGREENboth have the same value3If you use
enums, you address all these problems: