What are the advantages (or disadvantages) of having an enum
versus having a set of static final int
s in Java Android applications? Are there efficienc
Well... according to a bald guy Enums are really bad for memory.
You should use @IntDef/@StringDef annotations:
public static final int NAVIGATION_MODE_STANDARD = 0;
public static final int NAVIGATION_MODE_LIST = 1;
public static final int NAVIGATION_MODE_TABS = 2;
@IntDef({NAVIGATION_MODE_STANDARD, NAVIGATION_MODE_LIST, NAVIGATION_MODE_TABS})
public @interface NavigationMode {}
and then
@NavigationMode
public abstract int getNavigationMode();
public abstract void setNavigationMode(@NavigationMode int mode);
A very simple answer from personal experiences would be that Enums provide much better type safety or in other words the compiler gets to play a more active role in keeping your code bug free.
On the other hand, because Enums are "second-class citizens" of the object world, they can be difficult to use in some of the more subtle design patterns commonly used today, especially when generics are involved.
And finally, you can use static final ints in a bitfield. you couldnt do the following with an enum:
int selectedOptions = Options.OPTION1 | Options.OPTION2 | Options.OPTION3;
Enum advantages from this question:
- They are much more type-safe than integers, strings, or sets of boolean flags.
- They lead to more readable code.
- It's more difficult to set an enum to an invalid value than an int or string.
- They make it easy to discover the allowed values for a variable or parameter.
- Everything I've read indicates that they perform just as well as integers in C# and most JVMs.
I would add:
int
can't.Like most abstractions, they are generally unequivocally advantageous once their performance catches up. Especially in your application code (as opposed to framework code) I would choose enums over other methods that simulate them.
One advantage of ints over enums is in a CLASS FACTORY. The following C# code is not extensible:
class Factory
{
public enum DrawableType {CIRCLE,SQUARE};
public static Drawable GetInstance(DrawableEnum e)
{
if (e == DrawableType.CIRCLE)
{
return new Circle();
}
else if (e == DrawableType.SQUARE)
{
return new Square();
}
else
{
throw new IndexOutOfRangeException(); // should never get here
}
}
I wrote this poor code. Reviewing Design Patterns, the gang of four used an int. I tried to recover here.