创建字符串枚举的最佳方法?
让 enum
类型表示一组字符串的最佳方式是什么?
我尝试了这个:
enum Strings{
STRING_ONE("ONE"), STRING_TWO("TWO")
}
如何将它们用作字符串
?
What is the best way to have a enum
type represent a set of strings?
I tried this:
enum Strings{
STRING_ONE("ONE"), STRING_TWO("TWO")
}
How can I then use them as Strings
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
我不知道你想做什么,但这就是我实际翻译你的示例代码的方式......
或者,你可以为
text
创建一个 getter 方法。您现在可以执行
Strings.STRING_ONE.toString();
I don't know what you want to do, but this is how I actually translated your example code....
Alternatively, you can create a getter method for
text
.You can now do
Strings.STRING_ONE.toString();
枚举的自定义字符串值
来自 http://javahowto.blogspot.com/2006/10/custom-string-values-for-enum.html
java enum 的默认字符串值是它的面值或元素名称。但是,您可以通过重写 toString() 方法来自定义字符串值。例如,
运行以下测试代码将产生以下结果:
Custom String Values for Enum
from 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,
Running the following test code will produce this:
使用其
name()
方法:产生
ONE
。Use its
name()
method:yields
ONE
.将枚举名称设置为与您想要的字符串相同,或者更一般地,您可以将任意属性与枚举值相关联:
将常量放在顶部,将方法/属性放在底部,这一点很重要。
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:
It's important to have the constants at the top, and the methods/attributes at the bottom.
根据“将它们用作字符串”的含义,您可能不想在此处使用枚举。在大多数情况下,The Elite Gentleman 提出的解决方案将允许您通过其 toString 方法使用它们,例如在 System.out.println(STRING_ONE) 或 String s = "Hello " 中+STRING_TWO,但是当您确实需要字符串时(例如
STRING_ONE.toLowerCase()
),您可能更喜欢将它们定义为常量: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)
orString s = "Hello "+STRING_TWO
, but when you really need Strings (e.g.STRING_ONE.toLowerCase()
), you might prefer defining them as constants:您可以将其用于字符串枚举
并从主方法调用
You can use that for string Enum
And call from main method
如果您不想想要使用构造函数,并且想要为该方法指定一个特殊名称,请尝试这样做:
我怀疑这个是最快的解决方案。不需要使用变量final。
If you do not want to use constructors, and you want to have a special name for the method, try it this:
I suspect that this is the quickest solution. There is no need to use variables final.
使用默认值获取和设置。
Get and set with default values.