Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is Enum useful for? [duplicate]

Tags:

java

enums

After reading some questions and answers about enum I don't find it really useful...

It's something between class and a variable but I know where can I use it so it would be more useful then a class, or a couple of variables for example.

like image 509
Roni Copul Avatar asked Jul 09 '12 10:07

Roni Copul


People also ask

Can enum have duplicates?

CA1069: Enums should not have duplicate values.

What is the benefit of using enums?

The benefits of using enumerations include: Reduces errors caused by transposing or mistyping numbers. Makes it easy to change values in the future. Makes code easier to read, which means it is less likely that errors will creep into it.

What is the use of enum variable?

Enumeration or Enum in C is a special kind of data type defined by the user. It consists of constant integrals or integers that are given names by a user. The use of enum in C to name the integer values makes the entire program easy to learn, understand, and maintain by the same or even different programmer.

Why is enum better than constant?

Enums limit you to the required set of inputs whereas even if you use constant strings you still can use other String not part of your logic. This helps you to not make a mistake, to enter something out of the domain, while entering data and also improves the program readability.


2 Answers

There are other things you can do and reasons to use them, but the primary reason I use enums is to prevent the possibility of an invalid parameter. For example, imagine the following method:

public void doSomethingWithAMonth(int monthNum);

This is not only ambiguous (do month indexes start at 1, or at 0?), but you can give down-right invalid data (13+, negative numbers). If you have an enum Month with JAN, FEB, etc. the signature becomes:

public void doSomethignWithAMonth(Month month);

Code calling this method will be far more readable, and can't provide invalid data.

like image 165
Thor84no Avatar answered Nov 15 '22 21:11

Thor84no


I use Enums for anything that has multiple nonchanging "type" of something. i.e days of a week.

Why I don't use String in this case is because I can't do switch statement on the String and I can on Enum so for every day of a week I can do something specific.

I also use Enum when working with singleton pattern, Check the Effective Java book CH2(CHAPTER 2 CREATING AND DESTROYING OBJECTS), quote :

"While this approach has yet to be widely adopted, a single-element enum type is the best way to implement a singleton." not gonna paste code read the book it's excellent.

If I were you I'd firstly read Thinking in java chapter Enumerated Types. Then after that Effective Java chapter 6 and you should be good

like image 20
ant Avatar answered Nov 15 '22 22:11

ant