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 efficiency or performance optimizations that occur that favor the use of one or the other?
I ask this in context of say intent requestCodes and such - which tend to be ints in the Android sample code, as opposed to values from an enum, which I was used to in C.
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:
Well... according to a bald guy Enums are really bad for memory.
You should use @IntDef/@StringDef annotations:
and then
One advantage of ints over enums is in a CLASS FACTORY. The following C# code is not extensible:
I wrote this poor code. Reviewing Design Patterns, the gang of four used an int. I tried to recover here.
Enum advantages from this question:
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.