2012-07-18 6 views

답변

85
Week week = Week.SUNDAY; 

int i = week.ordinal(); 

선언에서 열거 형 상수의 순서를 변경하면이 값이 변경됩니다.

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); 
    } 
} 
+1

+1, 지금 당신은 5 년 이상 지각이 있습니까? ;) – avalancha

8

당신이 호출 할 수 있습니다 :

MONDAY.ordinal() 

을하지만 개인적으로 나는 enum에 속성을 추가 할이 문제를 얻는 하나의 방법이다 이런 식으로 모든 열거 상수에 int 값을 자동 지정 값을 저장하려면 enum 생성자에서 초기화하고 값을 가져 오는 함수를 추가하십시오. enum 상수를 이동하면 MONDAY.ordinal의 값이 변경 될 수 있기 때문에 더 좋습니다.

2

Take a look at the API 보통 시작하기에 알맞은 곳입니다. 비록 당신이 ENUM_NAME에 전화하기 전에 이것을 실행하지 않고 추측하지는 못했지만.()

0

그래, 간단히 ordinal enum 개체의 메서드를 사용하십시오.

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 :

1 라이너 이전 답변
+0

오년 후반이 아니라 더 나은 충분했을 것이다 멋진 대답을 제공

/** * 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; } 
Trilarion

+0

@Trilarion의보다 –

관련 문제