Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: enum vs static final ints?

What are the advantages (or disadvantages) of having an enum versus having a set of static final ints 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.

like image 529
Cubic Avatar asked Mar 09 '11 21:03

Cubic


People also ask

Are enums static and final?

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

Why use enum instead of constants?

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.


1 Answers

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:

  • Enums can have member and instance variables, whereas an 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.

like image 192
Matthew Willis Avatar answered Oct 07 '22 17:10

Matthew Willis