0

I am aware there are similar questions, and I have read the answers, but maybe I'm just not quite grasping the full difference of its use, even though I understand their difference when for example, initializing a String. Example:

String[] favorite = {"dog", "cat", "alien"};

vs

enum favorite = {dog, cat, alien}

Or maybe the use of either in the above case is similar, but their difference can be grasped better in another example? Is it that enum can clearly store more properties for a variable when creating the class?

DGonz
  • 31
  • 7
  • One reason might be that array is mutable. You or somebody who uses your API can modify its contents at will. If the values are constants then there is no need to use an array since you expect that they rarely or never change. – GPuschka Jun 29 '16 at 07:09
  • Able to use them in a switch, clarity of purpose. A string[] doesn't exactly work like an enum anyways, it doesn't create new types. – Natecat Jun 29 '16 at 07:10
  • @Natecat You can use strings in `switch` starting from java 7 – AhmadWabbi Jun 29 '16 at 07:11
  • @AhmadWabbi But you lose backwards compatbility – Natecat Jun 29 '16 at 07:13
  • @Natecat Who cares? `enum` itself did not exist before Java 5 – AhmadWabbi Jun 29 '16 at 07:14
  • There is a very similar question [here](http://stackoverflow.com/questions/4709175/what-are-enums-and-why-are-they-useful) (which I found by searching online for "java why use enum"). Does that answer your question? If not, please try to be more specific about what you don't understand about the pros/cons. Note that if you do understand the objective pros and cons, and just aren't sure they're "worth it"... then this is probably off-topic as being opinion-based. – yshavit Jun 29 '16 at 07:14
  • @yshavit As I mentioned in the title, I have read other answers, but I feel even though some are "complete in context", they are somewhat vague. As to being specific, I gave a specific example, do you really need me to be "more" specific, I mean I can try..? And third, this is not "just" opinion, although those are welcome. This is strictly so I can learn on what situations one cannot be used, or one is efficiently better than the other. I can see why you could confuse both intentions. So I'm not sure what your contribution is, but thanks for the link, it always helps to read new angles. ;) – DGonz Jun 29 '16 at 07:54

7 Answers7

2

The big advantage of enum is that the compiler checks for typos (type safety). For instance, if you assign the value "dag" to a string, the compiler does not complain. But, you cannot assign the value favorite.dag to a variable (of type favorit). Also, enum makes the code more readable and it is faster (comparison, for instance).

AhmadWabbi
  • 2,253
  • 1
  • 20
  • 35
  • The big advantage of an enum is it's capable of much more than a string array. – ChiefTwoPencils Jun 29 '16 at 07:18
  • Like what? What can you do with an `enum` that you cannot do with an array of string? I am discussing the use of `enum` in general, not specific to java – AhmadWabbi Jun 29 '16 at 07:22
  • Well, one can't limit the power of a Java enum to that of any other possible language's implementation of an enum; that would just be unfair (to Java); the question is tagged Java so I think it's reasonable to cite the differences. – ChiefTwoPencils Jun 29 '16 at 07:26
  • What I can't do with a string array that I can do with a Java enum is: `MyEnum.Something.doSomeCoolStuffNotProvidedByString();` – ChiefTwoPencils Jun 29 '16 at 07:31
  • @ChiefTwoPencils I think that, even though the question is tagged `java`, it has a general confusion regarding `enum` concept in general. This is why I kept the answer general. You are right, it is a cool stuff (methods in `enum`), but I never used it in my 20-year career in programming field :-) – AhmadWabbi Jun 29 '16 at 07:34
  • It's your answer so I'll leave it at that. I certainly won't argue with a a 20-year vet ;) – ChiefTwoPencils Jun 29 '16 at 07:40
  • @AhmadWabbi As I understand it, enum has some small differences in compiling/executing among different languages. Might be wrong, but that's what started my doubt. In Java, what would be the 'major' difference. But that's exactly my point, it "may" take some workarounds, but I find I can do "almost" everything I can do with a String[] array. Thanks, man for the contribution. – DGonz Jun 29 '16 at 07:40
  • @DGonz You are right. enums are implemented differently among languages. In C++, it is just type-checked by the compiler and converted into `int`. In Java, it is more complicated and sophisticated. You can do anything using any type (use `char` instead of `boolean`, `String` instead of `int`, ...), but using the "most appropriate" type facilitates the programmer's life and makes the program easier to read, to be brief. YW. – AhmadWabbi Jun 29 '16 at 07:59
  • 1
    @ChiefTwoPencils LOL. Thanks. – AhmadWabbi Jun 29 '16 at 08:02
  • Yeah, I'm probably going to start using 'enum' for these types of scenarios, since it seems more appropriate for both coding and reading code. I guess I just wanted to see if there was something specific that could not be done with either implementation that would facilitate differentiating-in-depth both concepts. – DGonz Jun 29 '16 at 08:03
2

Just like @AhmadWabbi said, it's mostly type safety.

With enums you also have the ability to write methods corresponding to the enum. For instance:

public enum Favorite = {
    dog("woof"), 
    cat("meow"),
    alien("zoink")

    private String sound;

    Favorite(String sound) {
        this.sound = sound;
    }

    public String makeSound() {
        return sound;
    }
}

Which then let you call the method on a known enum (Favorite.dog.makeSound()) or if the enum is a parameter to another method.

Robin Jonsson
  • 2,761
  • 3
  • 22
  • 42
  • Would this mean that method-calling takes more toll (on loading or time) for a program than initializing an 'enum' in the main method? – DGonz Jun 29 '16 at 07:46
  • @DGonz, this answer is significant for the differences. How could/would you implement this behavior using only a single string array in Java? – ChiefTwoPencils Jun 29 '16 at 08:19
  • @ChiefTwoPencils Thanks again, Chief. However my questions was specifically related to short lists and not method/class calling, which is why I added String examples. So technically, I didn't need to implement the above behavior anywhere. However, your answer among some others just gave me insight that there is no real difference in using either, *for my example*. Although additionally, I'm pretty sure I can call a method/class directly when I need it and not rely on 'enum', but I believe that would just take more code and using other concepts that 'enum' would probably just make easier. – DGonz Jun 29 '16 at 10:14
2

The biggest advantage is that an enum is type-safe. An enum value can only take on one of the defined values (or null). (Note that an enum in Java is not like an enum in C++ or C#, where it is more like an alias for an int).

If you use a type like String or int, you can assign to that any value that fits in a String or int, even if it's not one of the limited set of values that you want it to contain.

It also makes programs easier to read, because when for example a method takes an enum type as a parameter, you immediately know what it means, and what values are valid - if it would, for example, take a String, you don't automatically know which strings are valid inputs and which are not.

Jesper
  • 202,709
  • 46
  • 318
  • 350
  • Couldn't I make my program simply "filter" or have an exception for when an incorrectly-typed value is used? Would this then mean that one of the "only" major differences I can have with the 'enum' is that sometimes its less code to write for variable validation, and/or perhaps more specific? (Doesn't mean it cannot be done with an array). – DGonz Jun 29 '16 at 07:44
  • @DGonz Why check the values yourself at runtime (which means you have to write more code and it costs performance at runtime) when you can let the compiler do these checks for you at compile time? The earlier you catch errors the better; it's better to catch mistakes at compile time than at runtime. – Jesper Jun 29 '16 at 08:04
1

There is no need to be too sophisticated with a program. If you have three strings use the string array. If you have three distinct entities which differ by something else in addition to their names, use enum (on which you, evidently, will then be operating somehow).

Alexander Kulyakhtin
  • 47,782
  • 38
  • 107
  • 158
  • Yeah, that's what I wanted to know. If there was any additional major difference between both for this kind of purpose. But it seems more than the real difference lies in method/class calling and other method properties, if you sum up the answers. Thanks, though. – DGonz Jun 29 '16 at 07:45
1

Enums are easy to add new functionality to your code. Strings have their limits, you can decide yourself if you need all the benefits of enums or string will do for the job.

For example:

  public enum favourite {
    dog, cat, cow;

    public boolean barking(){
      switch(this){
        case dog:
          return true;
        case cat:
        case cow:  
          return false;
      }
      throw new AssertionError();
    }

  }
CsBalazsHungary
  • 803
  • 14
  • 30
1

Enum sort of create a namespace . Thus two constants with same name can belong to different enums. Of course , you can emulate it with ArrayList but its not intuitive , because its supposed to acts as a container rather than a logical namespace holding constants.

You can compare it old style enums from C++ , where two enum declarations holding a same named constant shows a error . With new style class enums in c++ adds sort of namespace to it , which was not possible earlier.

And yes Enums in Java already have a name-spacing feature. By the way , Enum and ArrayList both have different purpose.

Anil Soni
  • 167
  • 1
  • 9
  • Oh, I do understand each other's purpose in a way. I just find using 'enum' would probably be less frequent than I thought. However, your explanation of old style 'enum's kind of give me insight into thinking, this would probably be more convenient during multiple input programs where comparison of String values (or sure, any other) should probably be done safely and very accurately. Maybe I'm wrong? – DGonz Jun 29 '16 at 07:48
  • Here another analogy to convince you to use enums , which will probably make the difference more clear. So , In mySql or some dbms , they have a enum type , which is not essentially stored as a string but with a integer under the hood , which makes it use less space and what you got a clean and clear abstraction over the integers.Now you may say that you can use string there as well , which is true . But again you are wasting the precious space for nothing ! . enums groups constants which can be effectively represented by integers or shorts rather than full string. – Anil Soni Jun 30 '16 at 11:14
1

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";
Hoopje
  • 12,677
  • 8
  • 34
  • 50