35

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?

James Raitsev
  • 92,517
  • 154
  • 335
  • 470

4 Answers4

93
Week week = Week.SUNDAY;

int i = week.ordinal();

Be careful though, that this value will change if you alter the order of enum constants in the declaration. One way of getting around this is to self-assign an int value to all your enum constants like this:

public enum Week 
{
     SUNDAY(0),
     MONDAY(1)

     private static final Map<Integer,Week> lookup 
          = new HashMap<Integer,Week>();

     static {
          for(Week w : EnumSet.allOf(Week.class))
               lookup.put(w.getCode(), w);
     }

     private int code;

     private Week(int code) {
          this.code = code;
     }

     public int getCode() { return code; }

     public static Week get(int code) { 
          return lookup.get(code); 
     }
}
Istvan Devai
  • 3,962
  • 23
  • 21
9

You can call:

MONDAY.ordinal()

but personally I would add an attribute to the enum to store the value, initialize it in the enum constructor and add a function to get the value. This is better because the value of MONDAY.ordinal can change if the enum constants are moved around.

vainolo
  • 6,907
  • 4
  • 24
  • 47
2

Take a look at the API it is usually a decent place to start. Though I would not have guessed without having run into this before that you call ENUM_NAME.ordinal()

John Kane
  • 4,383
  • 1
  • 24
  • 42
0

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;
    }
Ganesa Vijayakumar
  • 2,422
  • 5
  • 28
  • 41