14. Enumerations

14.1. Basic

 1enum Gender {
 2  Male, Female
 3}
 4
 5public static class Person {
 6  private String firstName;
 7  private String lastName;
 8  private Gender gender;
 9
10  public Person(String firstName, String lastName, Gender gender) {
11    this.firstName = firstName;
12    this.lastName = lastName;
13    this.gender = gender;
14  }
15
16  public Gender getGender() { return gender; }
17
18  @Override
19  public String toString() {
20    return (new StringBuilder())
21        .append(firstName)
22        .append(' ')
23        .append(lastName)
24        .toString();
25  }
26}
 1Person[] people = {
 2    new Person("John", "Doe", Gender.Male),
 3    new Person("Jane", "Smith", Gender.Female)
 4};
 5
 6for (Person person : people) {
 7  switch (person.getGender()) {
 8    case Male -> System.out.println(person + " is a male");
 9    case Female -> System.out.println(person + " is a female");
10    default -> System.out.println(person + " has an unknown gender");
11  }
12}

14.2. Using valueOf

 1enum Gender {
 2  Male, Female
 3}
 4
 5public static class Person {
 6
 7  private String firstName;
 8  private String lastName;
 9  private Gender gender;
10
11  public Person(String firstName, String lastName, Gender gender) {
12    this.firstName = firstName;
13    this.lastName = lastName;
14    this.gender = gender;
15  }
16
17  public Gender getGender() {
18    return gender;
19  }
20
21  @Override
22  public String toString() {
23    return (new StringBuilder())
24        .append(firstName)
25        .append(' ')
26        .append(lastName)
27        .toString();
28  }
29}
 1Person[] people = {
 2    new Person("John", "Doe", Gender.valueOf("Male")),
 3    new Person("Jane", "Smith", Gender.valueOf("Female"))
 4};
 5
 6for (Person person : people) {
 7  switch (person.getGender()) {
 8    case Male -> System.out.println(person + " is a male");
 9    case Female -> System.out.println(person + " is a female");
10    default -> System.out.println(person + " has an unknown gender");
11  }
12}

14.3. Enumeration class

1import java.util.Random;
1enum Item {
2  Hat(5.00d), Shirt(10.00), Pants(15.00), Shoes(50.00), Socks(3.00);
3
4  private double price;
5
6  Item(double price) {
7    this.price = price;
8  }
9}
 1var items = Item.values();
 2
 3var purchases = new Item[3];
 4Random random = new Random(37L);
 5for (int i = 0; i < purchases.length; i++) {
 6  int index = random.nextInt(items.length);
 7  purchases[i] = items[index];
 8}
 9
10double total = 0.0d;
11for (Item item : purchases) {
12  total += item.price;
13}
14
15System.out.println(total);