开发者

Implementing toString on Java enums

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 co开发者_如何学Gompiler errors with it.

Thanks


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.

An enum in Java is basically a class that has a set number of instances.


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

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

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


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


I liked this approach for selective alternate toString() if it's useful for anyone out there :

private enum TrafficLight {
  RED,
  GREEN {
    @Override
    public String toString() {
        return "GREEN-ISH";
    }
  }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜