Java 创建字符串枚举的最佳方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3978654/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 07:51:48  来源:igfitidea点击:

Best way to create enum of strings?

javaenums

提问by Dori

What is the best way to have a enumtype represent a set of strings?

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

I tried this:

我试过这个:

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

How can I then use them as Strings?

那么我如何将它们用作Strings

采纳答案by Buhake Sindi

I don't know what you want to do, but this is how I actually translated your example code....

我不知道你想做什么,但这就是我实际翻译你的示例代码的方式......

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

Alternatively, you can create a getter method for text.

或者,您可以为text.

You can now do Strings.STRING_ONE.toString();

你现在可以做 Strings.STRING_ONE.toString();

回答by Bart Kiers

Use its name()method:

使用它的name()方法:

public class Main {
    public static void main(String[] args) throws Exception {
        System.out.println(Strings.ONE.name());
    }
}

enum Strings {
    ONE, TWO, THREE
}

yields ONE.

产量ONE

回答by Adrian Smith

Either set the enum name to be the same as the string you want or, more generally,you can associate arbitrary attributes with your enum values:

要么将枚举名称设置为与您想要的字符串相同,或者更一般地说,您可以将任意属性与您的枚举值相关联:

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

It's important to have the constants at the top, and the methods/attributes at the bottom.

将常量放在顶部,将方法/属性放在底部,这一点很重要。

回答by hd42

Depending on what you mean by "use them as Strings", you might not want to use an enum here. In most cases, the solution proposed by The Elite Gentleman will allow you to use them through their toString-methods, e.g. in System.out.println(STRING_ONE)or String s = "Hello "+STRING_TWO, but when you really need Strings (e.g. STRING_ONE.toLowerCase()), you might prefer defining them as constants:

根据“将它们用作字符串”的含义,您可能不想在此处使用枚举。在大多数情况下,精英绅士提出的解决方案将允许您通过它们的 toString 方法使用它们,例如 inSystem.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";      
}

回答by vaichidrewar

Custom String Values for Enum

枚举的自定义字符串值

from http://javahowto.blogspot.com/2006/10/custom-string-values-for-enum.html

来自http://javahowto.blogspot.com/2006/10/custom-string-values-for-enum.html

The default string value for java enum is its face value, or the element name. However, you can customize the string value by overriding toString() method. For example,

java enum 的默认字符串值是它的面值,或元素名称。但是,您可以通过覆盖 toString() 方法来自定义字符串值。例如,

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

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

Running the following test code will produce this:

运行以下测试代码将产生以下结果:

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

回答by Adam111p

If you do notwant to use constructors, and you want to have a special namefor the method, try it this:

如果你希望使用构造函数,你想有一个特殊的名字的方法,试试这个:

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

  public abstract String getDescription();
}

I suspect that this is the quickestsolution. There is no need to use variables final.

我怀疑这是最快的解决方案。不需要使用变量 final

回答by Shohel Rana

You can use that for string Enum

您可以将其用于字符串 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;
    }
}

And call from main method

并从主方法调用

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

回答by Pravin

Get and set with default values.

获取和设置默认值。

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