Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use Enum or Collection in Java

Tags:

Under what circumstances is an enum more appropriate than, for example, a Collection that guarantees unique elements (an implementer of java.util.Set, I guess...)?

(This is kind of a follow up from my previous question)

like image 845
brabster Avatar asked Jan 26 '09 19:01

brabster


People also ask

When should we use enum in Java?

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.

Why is enum not good?

It's hard to voice what your actual needs are to a potential partner for fear that they may write you off. Transparency requires over communication. If your communication skills are already not that great, ENM is going to be more of a headache than an opportunity to be your most authentic self.

Why enums are better than constants?

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

What is the purpose of using enum?

An enumeration, or Enum , is a symbolic name for a set of values. Enumerations are treated as data types, and you can use them to create sets of constants for use with variables and properties.


1 Answers

Basically when it's a well-defined, fixed set of values which are known at compile-time.

You can use an enum as a set very easily (with EnumSet) and it allows you to define behaviour, reference the elements by name, switch on them etc.

like image 125
Jon Skeet Avatar answered Oct 06 '22 19:10

Jon Skeet