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.
Enum in Java provides type-safety and can be used inside switch statements like int variables. Since enum is a keyword you can not use as a variable name and since it's only introduced in JDK 1.5 all your previous code which has an enum as a variable name will not work and needs to be refactored.
In Java (from 1.5), enums are represented using enum data type. Java enums are more powerful than C/C++ enums. In Java, we can also add variables, methods, and constructors to it. The main objective of enum is to define our own data types(Enumerated Data Types).
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:
if-then-else
with a final else throw new IllegalArgumentException("Unknown color " + color);
- again expensiveYELLOW
and GREEN
both have the same value 3
If you use enums
, you address all these problems:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With