001package enumeration;
002
003import java.util.Arrays;
004import java.util.Collections;
005import java.util.List;
006
007
008// Ordinal-based typesafe enum (From Bloch)
009//
010// No need to override equals, since only one instance of each suit.
011// Note that instanceNum and name are instance fields.
012// Note that cNumInstances is a class field.
013// Note that the order of the constant definitions is important.
014// Note that VALUES is an immutable collection.
015// Java arrays are always mutable :-(
016public final class Suit implements Comparable<Suit> {
017        // Number of instances
018        private static int cNumInstances = 0;
019
020        // Ordinal for this instance
021        private final int instanceNum;
022
023        // Name of Suit
024        private final String name;
025
026        // Private constructor: All instances created in the class
027        private Suit(String name) {
028                this.name = name;
029                this.instanceNum = Suit.cNumInstances++;
030        }
031
032        public String toString() {
033                return name;
034        }
035
036        public int compareTo(Suit that) {
037                return this.instanceNum - that.instanceNum;
038        }
039
040        public static final Suit CLUBS = new Suit("clubs");
041        public static final Suit DIAMONDS = new Suit("diamonds");
042        public static final Suit HEARTS = new Suit("hearts");
043        public static final Suit SPADES = new Suit("spades");
044
045        public static final List<Suit> VALUES;
046        static {
047                Suit[] values = { CLUBS, DIAMONDS, HEARTS, SPADES };
048                VALUES = Collections.unmodifiableList(Arrays.asList(values));
049        }
050}