在 Java 枚举上实现 toString

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2497521/
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-13 08:28:01  来源:igfitidea点击:

Implementing toString on Java enums

javaenums

提问by devoured elysium

It seems to be possible in Java to write something like this:

在 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?
  }
 }

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?:

现在,我想知道是否可以在枚举值为红色时返回 toString 方法“abc”和绿色时返回“def”。另外,是否可以像在 C# 中那样做,您可以在哪里执行此操作?:

 private enum TrafficLight {
  RED = 0,
  GREEN = 15
  ...
 }

I've tried this but it but I'm getting compiler errors with it.

我试过这个,但它但我收到编译器错误。

Thanks

谢谢

采纳答案by missingfaktor

Ans 1:

答案 1:

enum TrafficLight {
  RED,
  GREEN;

  @Override
  public String toString() {
    switch(this) {
      case RED: return "abc";
      case GREEN: return "def";
      default: throw new IllegalArgumentException();
    }
  }
}

Ans 2:

答案 2:

enum TrafficLight {
  RED(0),
  GREEN(15);

  int value;
  TrafficLight(int value) { this.value = value; }
}

回答by jjnguy

You can do it as follows:

你可以这样做:

private enum TrafficLight {
   // using the constructor defined below
   RED("abc"),
   GREEN("def");

   // Member to hold the name
   private String string;

   // constructor to set the string
   TrafficLight(String name){string = name;}

   // the toString just returns the given name
   @Override
   public String toString() {
       return string;
   }
}

You can add as many methods and members as you like. I believe you can even add multiple constructors. All constructors must be private.

您可以根据需要添加任意数量的方法和成员。我相信您甚至可以添加多个构造函数。所有构造函数都必须是private.

An enumin Java is basically a classthat has a set number of instances.

enumJava 中的an基本上是class具有一组实例的 a 。

回答by user3054516

Also if You need to get lowercase string value of enum ("red", "green") You can do it as follows:

此外,如果您需要获取枚举的小写字符串值(“红色”,“绿色”),您可以按如下方式进行:

private enum TrafficLight {
  RED,
  GREEN;

  @Override
  public String toString() {
   return super.toString().toLowerCase();
  }
}