2. Enums
• An enum type is a type whose fields consist of
a fixed set of constants.
• The names of an enum type's fields are in
uppercase letters.
• Example:
public enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY
}
3. When to use Enums
• Use an Enum any time you need to represent
a fixed set of constants.
• Examples:
Months of Year
Days of Week
Entries in a Menu
Colors
Directions of Compass
4. Enums (contd…)
• Enums are like classes, they can have fields
(state) and methods (behavior).
• All enums implicitly extend java.lang.Enum.
Since Java does not support multiple
inheritance, an enum cannot extend anything
else.
• Typesafe => compile-time error checking.
• You can use a switch on enum values.
5. Enums (contd…)
• toString() returns the enum value as a
String — can be overridden.
• values() method returns an array of all the
enum values.
• Can be used in collections as objects more
efficiently than int values — no
boxing/unboxing required!
• Implement the Comparable and Serializable
interfaces.
6. High Performance Set and Map
implementations for Enums
• EnumSet
All of the members of an EnumSet must be of the same
enum type.
Supports iteration over a range of enum types.
• EnumMap
Almost the same speed as an array.
If you want to map an enum to a value, use an EnumMap
instead of an array.
EnumMap's implementation uses an array and for that
reason has slightly better performance than HashMaps.