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.
An enum can, just like a class , have attributes and methods. The only difference is that enum constants are public , static and final (unchangeable - cannot be overridden). An enum cannot be used to create objects, and it cannot extend other classes (but it can implement interfaces).
Enums are lists of constants. When you need a predefined list of values which do represent some kind of numeric or textual data, you should use an enum. You should always use enums when a variable (especially a method parameter) can only take one out of a small set of possible values.
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.
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