使enum
类型表示一组字符串的最佳方法是什么?
我试过这个:
enum Strings{
STRING_ONE("ONE"), STRING_TWO("TWO")
}
Run Code Online (Sandbox Code Playgroud)
我怎么能用它们Strings
呢?
Buh*_*ndi 592
我不知道你想做什么,但这就是我实际翻译你的示例代码的方式....
/**
*
*/
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;
}
}
Run Code Online (Sandbox Code Playgroud)
或者,您可以为其创建getter方法text
.
你现在可以做 Strings.STRING_ONE.toString();
vai*_*war 101
枚举的自定义字符串值
来自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";
}
}
}
Run Code Online (Sandbox Code Playgroud)
运行以下测试代码将产生以下结果:
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
Run Code Online (Sandbox Code Playgroud)
Bar*_*ers 66
使用它的name()
方法:
public class Main {
public static void main(String[] args) throws Exception {
System.out.println(Strings.ONE.name());
}
}
enum Strings {
ONE, TWO, THREE
}
Run Code Online (Sandbox Code Playgroud)
收益率ONE
.
Adr*_*ith 16
将枚举名称设置为与所需的字符串相同,或者更一般地,您可以将任意属性与枚举值相关联:
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.
}
Run Code Online (Sandbox Code Playgroud)
将常量放在顶部,将方法/属性放在底部是很重要的.
hd4*_*d42 14
根据你的意思"将它们用作字符串",你可能不想在这里使用枚举.在大多数情况下,The Elite Gentleman提出的解决方案将允许您通过其toString方法使用它们,例如在System.out.println(STRING_ONE)
或中String s = "Hello "+STRING_TWO
,但是当您真正需要Strings(例如STRING_ONE.toLowerCase()
)时,您可能更喜欢将它们定义为常量:
public interface Strings{
public static final String STRING_ONE = "ONE";
public static final String STRING_TWO = "TWO";
}
Run Code Online (Sandbox Code Playgroud)
如果你不希望使用构造函数,你想有一个特殊的名字的方法,试试这个:
public enum MyType {
ONE {
public String getDescription() {
return "this is one";
}
},
TWO {
public String getDescription() {
return "this is two";
}
};
public abstract String getDescription();
}
Run Code Online (Sandbox Code Playgroud)
我怀疑这是最快的解决方案。不需要使用变量 final。
您可以将其用于字符串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;
}
}
Run Code Online (Sandbox Code Playgroud)
并从主要方法调用
public class Test {
public static void main (String args[]){
System.out.println(EnumTest.NAME_ONE.getName());
System.out.println(EnumTest.NAME_TWO.getName());
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
447125 次 |
最近记录: |