The biggest advantage of enums is that they are type-safe: a variable of an enum type can only hold values defined in that enum. By the way, in some circumstances this can be a big disadvantage, a show-stopper even: if the possible values are not known at compile time (for example, because you need to fetch them from a database at run-time) you cannot use enums.
Although I do not see a clear advantage of it (and if I don't see a clear advantage I would always use the established coding practice, which is using an enum), you can certainly use strings as a kind of enums. Performance will probably be a bit worse because of the string comparisons, but in most cases unnoticeably so.
However, I would strictly advice against your array example, for the following reasons:
- Arrays are mutable. If your project is large enough, someone will eventually write
favorites[0] = "beer";
and thus cause mysterious bugs in unrelated parts of the code.
- Using an array has no advantage in readability. The meaning
String myFavorite = favorites[1];
is completely opaque, whereas String myFavorite = "cat";
or Favorite myFavorite = Favorite.CAT;
are immediately clear.
- String literals can be used in
switch
statements, but not expressions like favorites[2]
. So switch (myFavorite) { case favorites[2]: ... }
is not legal Java (whereas switch (myFavorite) { case "alien": ... }
is).
If you really want to use Strings as enums, then define String constants:
public static final String FAV_DOG = "dog";
public static final String FAV_CAT = "cat";
public static final String FAV_ALIEN = "alien";