Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Enum vs. Int

Tags:

java

enums

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?

like image 386
Flynn Avatar asked Feb 13 '12 01:02

Flynn


People also ask

Should I use enum or int?

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.

Are enums in Java ints?

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.

Is enum still used in Java?

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).


1 Answers

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
like image 105
Bohemian Avatar answered Oct 01 '22 10:10

Bohemian