Created: 2023-09-06 15:19
Status: #concept
Subject: Programming
Tags: Java Java Data Type

Java Enum

It represents values that have a Set of specific values.

  • all the values in a public enum Name { VAL, ANOTHER, ... } will become static final constants within the Name class.
  • they should be defined in their own file like Java Classes and Java Interfaces.
  • using the .ordinal() method returns the int representation of the enum like in other programming languages.
  • they implement the java.util.Collection interface and can be interated through.
  • by default, the toString() value is the enum constant name.

public enum Suit {
    DIAMOND, SPADE, CLUB, HEART
}
public class Card {

    private int value;
    private Suit suit;

    public Card(int value, Suit suit) {
        this.value = value;
        this.suit = suit;
    }

    @Override
    public String toString() {
        return suit + " " + value;
    }

    public Suit getSuit() {
        return suit;
    }

    public int getValue() {
        return value;
    }
}
Card first = new Card(10, Suit.HEART);

System.out.println(first);

if (first.getSuit() == Suit.SPADE) {
    System.out.println("is a spade");
} else {
    System.out.println("is not a spade");
}

Custom Enumerated Values

public enum Color {
    // constructor parameters are defined as
    // the constants are enumerated
    RED("#FF0000"),
    GREEN("#00FF00"),
    BLUE("#0000FF");

    private String code;        // object reference variable

    private Color(String code) { // constructor
        this.code = code;
    }

    public String getCode() {
        return this.code;
    }
}
System.out.println(Color.GREEN.getCode()); // #00FF00

Iterating with a Collections.iterator()

public void print(){
    Iterator<Card> iterator = cards.iterator();

    while (iterator.hasNext()) {
        Card nextInLine = iterator.next();
        System.out.println(nextInLine);
    }
}

References