Απαρίθμηση ως κλάση
Η αντίστοιχη κλάση χωρίς τη χρήση απαρίθμησης θα είχε την παρακάτω μορφή.
public class Ingredients {
// Static array to hold all ingredient constants
private static final Ingredients[] VALUES = new Ingredients[7];
// Constants with names and ordinal values
public static final Ingredients TOMATO = new Ingredients("TOMATO", 0);
public static final Ingredients ONION = new Ingredients("ONION", 1);
public static final Ingredients TZATZIKI = new Ingredients("TZATZIKI", 2);
public static final Ingredients POTATO = new Ingredients("POTATO", 3);
public static final Ingredients MUSTARD = new Ingredients("MUSTARD", 4);
public static final Ingredients SOUVLAKI = new Ingredients("SOUVLAKI", 5);
public static final Ingredients GYROS = new Ingredients("GYROS", 6);
private final String name;
private final int ordinal;
private Ingredients(String name, int ordinal) {
this.name = name;
this.ordinal = ordinal;
VALUES[ordinal] = this; // Add to the static array
}
// Getters
public int ordinal() {
return ordinal;
}
public String getName() {
return name;
}
public static Ingredients[] values() {
return VALUES.clone(); // Return a copy of the array
}
public static Ingredients valueOf(String name) {
for (Ingredients ingredient : VALUES) {
if (ingredient.name.equals(name)) {
return ingredient;
}
}
throw new IllegalArgumentException("No enum constant " + name);
}
@Override
public String toString() {
return name;
}
}