2011-03-11 125 views

回答

2
enum MyConstants { 
    STR1("some text"), 
    STR2("some other text"); 

    private String value; 
    private MyConstants(String str) { 
    this.value = str; 
    } 
    public String getValue() { 
    return value; 
    } 
} 

然後使用它是這樣的:

MyConstants.STR1.getValue(); 
+0

爲什麼'toString()'而不是'getValue()'? – jtahlborn 2011-03-11 01:34:51

+0

沒有特別的理由。我只是展示瞭如何以類似於普通類的方式使用枚舉,並且可以使用相同的模式存儲多個枚舉值的單個屬性。 – iluxa 2011-03-11 01:42:25

0

我覺得這個頁面會有所幫助: http://javahowto.blogspot.com/2006/10/custom-string-values-for-enum.html

簡而言之:

public enum MyType { 
ONE { 
    public String toString() { 
     return "this is one"; 
    } 
}, 

TWO { 
    public String toString() { 
     return "this is two"; 
    } 
} 
} 
+0

與包含一串字符串的類相比,像這樣使用枚舉是否有優勢? – user496949 2011-03-11 01:36:57

+3

你想用字符串做什麼?舉例來說,枚舉可以用在switch語句中,並且可以有方法(甚至可以不同於每個枚舉) – 2011-03-11 01:38:36

1
String [] messages = {"maybe you", "better go with", "an array?"}; 
System.out.println (messages[1]); 

如果沒有進一步的知識 - e - 你爲什麼喜歡使用枚舉?

+0

因爲它們更好。閱讀此:http://download.oracle.com/javase/1.5.0/docs/guide/language/enums.html – iluxa 2011-03-11 01:43:47

+0

更好的是什麼?用於存儲字符串?當然不是。 – 2011-03-11 01:45:13

+0

對於編譯時安全類型 - Joshua Bloch – sarahTheButterFly 2011-03-11 04:26:56