2012-07-18 21 views

उत्तर

85
Week week = Week.SUNDAY; 

int i = week.ordinal(); 

हालांकि सावधान रहें, अगर आप घोषणा में enum स्थिरांक के क्रम को बदलते हैं तो यह मान बदल जाएगा। इस के आसपास हो रही का एक तरीका यह करने के लिए है इस तरह से अपने सभी enum स्थिरांक के लिए एक पूर्णांक मूल्य आत्म आवंटित:

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-लाइनर – avalancha

8

आप कॉल कर सकते हैं:

MONDAY.ordinal() 

लेकिन व्यक्तिगत रूप से मैं enum को एक विशेषता जोड़ना होगा मूल्य को स्टोर करने के लिए, इसे enum कन्स्ट्रक्टर में प्रारंभ करें और मान प्राप्त करने के लिए एक फ़ंक्शन जोड़ें। यह बेहतर है क्योंकि का मान बदल सकता है यदि enum स्थिरांक चारों ओर स्थानांतरित हो जाते हैं।

2

Take a look at the API यह आमतौर पर शुरू करने के लिए एक सभ्य स्थान है। हालांकि इससे पहले कि आप ENUM_NAME.ordinal()

0

हाँ कहें, तो बस क्रमशः एनम ऑब्जेक्ट की विधि का उपयोग करें।

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()); 
    } 

} 

एपीआई:

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

5 साल देर से और बेहतर नहीं पर्याप्त हो गया होता पिछले जवाब – Trilarion

+0

@Trilarion में से किसी की तुलना में प्रदान करने के लिए +1, अब आप 5+ साल देर हो चुके हैं क्या आपके पास कोई बेहतर जवाब है? ;) –

संबंधित मुद्दे