让枚举类型表示一组字符串的最佳方法是什么?
我试了一下:
enum Strings{
STRING_ONE("ONE"), STRING_TWO("TWO")
}
然后我如何使用它们作为字符串?
让枚举类型表示一组字符串的最佳方法是什么?
我试了一下:
enum Strings{
STRING_ONE("ONE"), STRING_TWO("TWO")
}
然后我如何使用它们作为字符串?
当前回答
如果你不想使用构造函数,并且你想为这个方法取一个特殊的名字,试试这个方法:
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;
}
}
如果你不想使用构造函数,并且你想为这个方法取一个特殊的名字,试试这个方法:
public enum MyType {
ONE {
public String getDescription() {
return "this is one";
}
},
TWO {
public String getDescription() {
return "this is two";
}
};
public abstract String getDescription();
}
我怀疑这是最快的解决办法。没有必要使用变量final。
使用它的name()方法:
public class Main {
public static void main(String[] args) throws Exception {
System.out.println(Strings.ONE.name());
}
}
enum Strings {
ONE, TWO, THREE
}
收益率。
我不知道你想做什么,但这就是我如何翻译你的示例代码....
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;
}
}
或者,也可以为文本创建getter方法。
你现在可以执行Strings.STRING_ONE.toString();
Enum的自定义字符串值
从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