![](/img/trans.png)
[英]What is the best way to create a simple Java Enum representing a constant set of strings
[英]Best way to create enum of strings?
讓enum
類型表示一組字符串的最佳方法是什么?
我試過這個:
enum Strings{
STRING_ONE("ONE"), STRING_TWO("TWO")
}
我怎樣才能將它們用作Strings
?
我不知道你想做什么,但這就是我實際翻譯你的示例代碼的方式......
package test;
/**
* @author The Elite Gentleman
*
*/
public enum Strings {
STRING_ONE("ONE"),
STRING_TWO("TWO")
;
private final String text;
/**
* @param text
*/
Strings(final String text) {
this.text = text;
}
/* (non-Javadoc)
* @see java.lang.Enum#toString()
*/
@Override
public String toString() {
return text;
}
}
或者,您可以為text
創建一個 getter 方法。
你現在可以做Strings.STRING_ONE.toString();
枚舉的自定義字符串值
來自http://javahowto.blogspot.com/2006/10/custom-string-values-for-enum.html
java enum 的默認字符串值是它的面值,或元素名稱。 但是,您可以通過覆蓋 toString() 方法來自定義字符串值。 例如,
public enum MyType {
ONE {
public String toString() {
return "this is one";
}
},
TWO {
public String toString() {
return "this is two";
}
}
}
運行以下測試代碼將產生以下結果:
public class EnumTest {
public static void main(String[] args) {
System.out.println(MyType.ONE);
System.out.println(MyType.TWO);
}
}
this is one
this is two
使用它的name()
方法:
public class Main {
public static void main(String[] args) throws Exception {
System.out.println(Strings.ONE.name());
}
}
enum Strings {
ONE, TWO, THREE
}
產生ONE
。
要么將枚舉名稱設置為與您想要的字符串相同,或者更一般地說,您可以將任意屬性與您的枚舉值相關聯:
enum Strings {
STRING_ONE("ONE"), STRING_TWO("TWO");
private final String stringValue;
Strings(final String s) { stringValue = s; }
public String toString() { return stringValue; }
// further methods, attributes, etc.
}
將常量放在頂部,將方法/屬性放在底部很重要。
根據“將它們用作字符串”的含義,您可能不想在此處使用枚舉。 在大多數情況下,精英紳士提出的解決方案將允許您通過它們的 toString 方法使用它們,例如在System.out.println(STRING_ONE)
或String s = "Hello "+STRING_TWO
,但是當您確實需要字符串時 (例如STRING_ONE.toLowerCase()
),您可能更喜歡將它們定義為常量:
public interface Strings{
public static final String STRING_ONE = "ONE";
public static final String STRING_TWO = "TWO";
}
您可以將其用於字符串 Enum
public enum EnumTest {
NAME_ONE("Name 1"),
NAME_TWO("Name 2");
private final String name;
/**
* @param name
*/
private EnumTest(final String name) {
this.name = name;
}
public String getName() {
return name;
}
}
並從主方法調用
public class Test {
public static void main (String args[]){
System.out.println(EnumTest.NAME_ONE.getName());
System.out.println(EnumTest.NAME_TWO.getName());
}
}
如果你不希望使用構造函數,你想有一個特殊的名字的方法,試試這個:
public enum MyType {
ONE {
public String getDescription() {
return "this is one";
}
},
TWO {
public String getDescription() {
return "this is two";
}
};
public abstract String getDescription();
}
我懷疑這是最快的解決方案。 不需要使用變量 final 。
獲取和設置默認值。
public enum Status {
STATUS_A("Status A"), STATUS_B("Status B"),
private String status;
Status(String status) {
this.status = status;
}
public String getStatus() {
return status;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.