What is the advantage of using enums over ints? I'm trying to represent the suits in a card game, and I thought 1,2,3,4 would be good enough. But my boss says I need to do it with enums. Why?
-
What suit maps to 1? Not very intuitive. If I define an enum with suits `SPADES` etc, much more readable. – C.B. Mar 20 '14 at 21:58
-
1. meaningful names, 2. they are also classes in their own right, with methods. Consider `TimeUnit`: `TimeUnit.SECONDS.sleep(10L)` – fge Mar 20 '14 at 22:00
-
[Type safety](http://en.wikipedia.org/wiki/Type_safety)! – Jesper Mar 20 '14 at 22:03
3 Answers
Enums are good because they remove "magic numbers"- numbers that don't really mean anything on their own. By replacing those numbers with actual values, your code makes more sense and follows better design principles.
Also, enums prevent incorrect values from being passed to a function. If your enum only defines Spades, Hearts, Clubs
, and Diamonds
, then only objects of the enum can be passed.

- 7,888
- 6
- 32
- 52
If you use int
s, then what does the suit 5
mean? You'll have to handle that case. What if a caller sees int
and accidentally passes 2
attempting to create a "deuce"? Just using int
s, the same number may represent more than one valid, different value in different domains.
It is more typesafe to use an enum. It can only have your own pre-defined values, and the different type name disallows accidentally passing a valid value from another domain to your restricted domain of values.

- 176,041
- 30
- 275
- 357
enum
in java provides compile time check. So if you pass 100
in your program it will compile but fail at run time. An enum
will make sure this does not happen.

- 39,895
- 28
- 133
- 186