在 Java 枚举上实现 toString
在Java中似乎可以写这样的东西:
private enum TrafficLight {
RED,
GREEN;
public String toString() {
return //what should I return here if I want to return
//"abc" when red and "def" when green?
}
}
现在,我想知道当枚举的值为红色时是否可以在toString方法中返回“abc”,当枚举的值为绿色时返回“def”。另外,是否可以像在 C# 中一样,在哪里可以执行此操作?:
private enum TrafficLight {
RED = 0,
GREEN = 15
...
}
我已尝试过此操作,但出现编译器错误。
谢谢
It seems to be possible in Java to write something like this:
private enum TrafficLight {
RED,
GREEN;
public String toString() {
return //what should I return here if I want to return
//"abc" when red and "def" when green?
}
}
Now, I'd like to know if it possible to returnin the toString method "abc" when the enum's value is red and "def" when it's green. Also, is it possible to do like in C#, where you can do this?:
private enum TrafficLight {
RED = 0,
GREEN = 15
...
}
I've tried this but it but I'm getting compiler errors with it.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以按如下方式进行操作:
您可以添加任意数量的方法和成员。我相信你甚至可以添加多个构造函数。所有构造函数都必须是
私有
。Java 中的
enum
基本上是一个具有一定数量实例的类
。You can do it as follows:
You can add as many methods and members as you like. I believe you can even add multiple constructors. All constructors must be
private
.An
enum
in Java is basically aclass
that has a set number of instances.答案 1:
答案 2:
Ans 1:
Ans 2:
另外,如果您需要获取枚举的小写字符串值(“red”,“green”),您可以按如下方式执行:
Also if You need to get lowercase string value of enum ("red", "green") You can do it as follows:
我喜欢这种选择性替代 toString() 的方法,如果它对任何人都有用的话:
I liked this approach for selective alternate toString() if it's useful for anyone out there :