How to get enum's numeric value?

Viewed 51912

Suppose you have

public enum Week {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}

How can one get int representing that Sunday is 0, Wednesday is 3 etc?

4 Answers

Yeah, Simply use the ordinal method of enum object.

public class Gtry {
  enum TestA {
    A1, A2, A3
  }

  public static void main(String[] args) {
    System.out.println(TestA.A2.ordinal());
    System.out.println(TestA.A1.ordinal());
    System.out.println(TestA.A3.ordinal());
  }

}

API:

/**
     * Returns the ordinal of this enumeration constant (its position
     * in its enum declaration, where the initial constant is assigned
     * an ordinal of zero).
     *
     * Most programmers will have no use for this method.  It is
     * designed for use by sophisticated enum-based data structures, such
     * as {@link java.util.EnumSet} and {@link java.util.EnumMap}.
     *
     * @return the ordinal of this enumeration constant
     */
    public final int ordinal() {
        return ordinal;
    }
Related