Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing toString on Java enums

Tags:

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 compiler errors with it.

Thanks

like image 418
devoured elysium Avatar asked Mar 23 '10 04:03

devoured elysium


People also ask

Can enum have toString?

The Java Enum has two methods that retrieve that value of an enum constant, name() and . toString(). The toString() method calls the name() method which returns the string representation of the enum constant.

What happens when you toString an enum?

ToString(String)Converts the value of this instance to its equivalent string representation using the specified format.

Can we override toString method in enum?

The toString() method of Enum class returns the name of this enum constant, as the declaration contains. The toString() method can be overridden, although it's not essential.


2 Answers

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.

like image 82
jjnguy Avatar answered Sep 18 '22 16:09

jjnguy


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; } } 
like image 43
missingfaktor Avatar answered Sep 16 '22 16:09

missingfaktor