Implementing toString on Java enums

JavaEnums

Java Problem Overview


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

Java Solutions


Solution 1 - Java

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.

Solution 2 - Java

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

Solution 3 - Java

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

Solution 4 - Java

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questiondevoured elysiumView Question on Stackoverflow
Solution 1 - JavajjnguyView Answer on Stackoverflow
Solution 2 - JavamissingfaktorView Answer on Stackoverflow
Solution 3 - Javauser3054516View Answer on Stackoverflow
Solution 4 - JavamudView Answer on Stackoverflow