Sub topic 1
Your First Enum: Named Constants Done Right
An enum is a type with a fixed list of named values. The days of the week are a good example: there are seven, and there will never be an eighth. An enum stops you from passing a wrong value, such as the string "Fryday", because the compiler only accepts real constants.
Declaring an Enum
A constant is a value that never changes. You list the constants inside the enum.
enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }
public class Main {
public static void main(String[] args) {
for (Day d : Day.values()) {
System.out.println(d.ordinal() + " " + d.name());
}
Day friday = Day.valueOf("FRIDAY");
System.out.println(friday == Day.FRIDAY); // true
}
}Every enum gets these methods for free:
| Method | What it does |
|---|---|
| `values()` | Returns all constants in order |
| `name()` | Returns the constant's name as text |
| `ordinal()` | Returns its position, starting at 0 |
| `valueOf("X")` | Turns text back into a constant |
Each constant exists only once, so it is safe to compare constants with ==.
Switching on Enums
A switch expression picks a result based on a value. If you cover every constant, you don't need a default branch.
static boolean isWeekend(Day day) {
return switch (day) {
case SATURDAY, SUNDAY -> true;
case MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY -> false;
};
}Giving Constants Data
A field is a variable stored inside an object. An enum can have fields and a constructor. Each constant passes its own value to that constructor.
enum Coin {
PENNY(1), NICKEL(5), DIME(10), QUARTER(25);
private final int cents;
Coin(int cents) {
this.cents = cents;
}
public int cents() {
return cents;
}
}Coin.DIME.cents() returns 10.
EnumSet and EnumMap
EnumSet is a set built for enum constants. EnumMap is a map whose keys are enum constants. Both are smaller and faster than HashSet and HashMap.
import java.util.EnumMap;
import java.util.EnumSet;
public class Hours {
public static void main(String[] args) {
EnumSet<Day> weekend = EnumSet.of(Day.SATURDAY, Day.SUNDAY);
EnumSet<Day> weekdays = EnumSet.complementOf(weekend);
EnumMap<Day, Integer> hours = new EnumMap<>(Day.class);
hours.put(Day.MONDAY, 8);
hours.put(Day.TUESDAY, 6);
System.out.println(weekdays); // [MONDAY, ... FRIDAY]
System.out.println(hours); // {MONDAY=8, TUESDAY=6}
}
}complementOf returns every constant that is not in the set you give it.
Exercise
What does Day.SUNDAY.ordinal() return, and why is it risky to save ordinals in a database?
Show answer
It returns 6. If someone reorders the constants or inserts a new one, the ordinals change, and the saved numbers then point to the wrong days. Store name() instead.
Exercise
Add a method to Coin that returns true when the coin is worth more than 5 cents.
Show answer
Add public boolean isLarge() { return cents > 5; } inside the enum. Then Coin.DIME.isLarge() returns true and Coin.PENNY.isLarge() returns false.