tags:

views:

1677

answers:

6

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)

Thanks!

+11  A: 

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.

Jon Skeet
Thanks for that link to EnumSet - missed that before now.
Brabster
EnumSet and EnumMap rock.
Hank Gay
I'd never seen EnumMap before - even though I frequently use EnumSet!
Jon Skeet
Yeah I only stumbled across EnumMap last year. Good class.
cletus
@JonSkeet- Sir, do you think .net world still needs to learn from bros from Java world??
Perpetualcoder
@Perpetualcoder: Absolutely when it comes to enums. Java enums are much nicer than C#/.NET enums.
Jon Skeet
+2  A: 

I am no java guru, but my guess is to use enumeration when you want to gurantee a certain pool of values, and to use a collection when you want to gurantee uniqueness. Example would be to enumerate days of the week (cant have "funday") and to have a collection of SSN (generic example i know!)

+2  A: 

When the elements are known up front and won't change, an enum is appropriate.

If the elements can change during runtime, use a Set.

duffymo
+1  A: 

Great responses - I'll try and summarise, if just for my own reference - it kinda looks like you should use enums in two situations:

All the values you need are known at compile time, and either or both of the following:

  • you want better performance than your usual collection implementations
  • you want to limit the potential values to those specified at compile time

With the Collection over enumeration links that Jon gave, you can get the benefits of enum performance and safety as an implementation detail without incorporating it into your overall design.

Community wiki'd, please do edit and improve if you want to!

Brabster
In addition a single-member enum makes a great singleton. Assuming you really want a singleton.
Darron
A: 

In some situations your business requires the creation of new items, but at the same time business logic based on some fixed items. For the fixed ones you want an enum, the new ones obviously require some kind of collection/db.

I've seen projects using a collection for this kind of items, resulting in business logic depending on data which can be deleted by the user. Never do this, but do create a separate enum for the fixed ones and a collection for the others, just as required.

An other solution is to use a collection with immutable objects for the fixed values. These items could also reside in a db, but have an extra flag so users cannot update / delete it.

Jurgen H
A: 

Note: you can have both with an EnumSet.

Peter Lawrey