This seems like it would be a common question, but none of the items in the suggestion box exactly explained what I am wondering. In this link, everyone suggested using the enum type (which I’ve now researched, but never used prior). I was about to suggest simply using a HashMap and read the answers to see if the Enum ( http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html ) was ,in fact, a better answer. According to that link on oracle, “You should use enum types any time you need to represent a fixed set of constants.” So, it is.
My question is… why? Is it more of forming a contract that they will not change? Is it a shorter way of getting some class functionality? How’s the performance? Why is this any different than just defining the constants in the same class?
Thank you!
Enum instances are objects, encapsulating data and behaviour just like any other object. By passing enum instances around, anyone can call its methods. If you pass Map keys as Strings, for example, you can’t do anything useful with the key. Moreover, the code is less type-safe, and less self-documenting, since the String could very well be something completely different from what it’s supposed to be.
What’s the most readable?
or
What if I pass something other than a month name in the set?