让枚举类型表示一组字符串的最佳方法是什么?

我试了一下:

enum Strings{
   STRING_ONE("ONE"), STRING_TWO("TWO")
}

然后我如何使用它们作为字符串?


当前回答

根据你所说的“使用它们作为字符串”,你可能不想在这里使用enum。在大多数情况下,精英绅士提出的解决方案将允许你通过他们的tostring -方法使用它们,例如在System.out.println(STRING_ONE)或Strings = "Hello "+STRING_TWO,但当你真的需要字符串(例如STRING_ONE. tolowercase()),你可能更喜欢将它们定义为常量:

public interface Strings{
  public static final String STRING_ONE = "ONE";
  public static final String STRING_TWO = "TWO";      
}

其他回答

根据你所说的“使用它们作为字符串”,你可能不想在这里使用enum。在大多数情况下,精英绅士提出的解决方案将允许你通过他们的tostring -方法使用它们,例如在System.out.println(STRING_ONE)或Strings = "Hello "+STRING_TWO,但当你真的需要字符串(例如STRING_ONE. tolowercase()),你可能更喜欢将它们定义为常量:

public interface Strings{
  public static final String STRING_ONE = "ONE";
  public static final String STRING_TWO = "TWO";      
}

获取和设置默认值。

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

使用它的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();

你可以将它用于string 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;
    }
}

并从main方法调用

public class Test {
    public static void main (String args[]){
        System.out.println(EnumTest.NAME_ONE.getName());
        System.out.println(EnumTest.NAME_TWO.getName());
    }
}