4

Given the following :

enum Moving {DownRight , UpRight ,DownLeft ,UpLeft ,Up , Down ,Left ,Right};

Moving m_moving;

If I do for example :

m_moving = Moving.DownRight;

and

m_moving.toString();

Then I'll get :

DownRight

So ,how can I add a description for each entry in the enum ?

For example , if I'd do m_moving.toString(); then I want to present FOO BAR .

Thanks

JAN
  • 21,236
  • 66
  • 181
  • 318
  • 1
    Or look at the [official tutorial](http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html). Enums can have fields and constructors like any other class. – Russell Zahniser Apr 13 '13 at 15:20
  • 1
    By the way, I'd recommend you order your directions in clockwise rotation, for example e/se/s/sw/w/nw/n/ne. This gives you the nice property that if you take an enumeration value, add 4 to it and take it % 8 then you get the opposite direction. Plus other useful related properties. – Patashu Apr 13 '13 at 15:20
  • This is also a great post : http://stackoverflow.com/questions/9662170/java-override-valueof-and-tostring-in-enum – JAN Apr 13 '13 at 15:34

2 Answers2

12

Look at this code, from our application

public enum RegimeTributario {
    SIMPLES_NACIONAL("SI"), 
    LUCRO_PRESUMIDO("LP"), 
    LUCRO_REAL("LR");

    private String sigla;

    private RegimeTributario(String sigla) {
        this.sigla = sigla;
    }

    public String getSigla() {
        return sigla;
    }
}

enums accept fields too

Luiz E.
  • 6,769
  • 10
  • 58
  • 98
6

Following this post , here is my final answer (also , big thanks to @Luiz E.):

enum DirectionsEnum {

    North("North"),
    NorthEast("North East"),
    East("East"),
    SouthEast("South East"),
    South("South"),
    SouthWest("South West"),
    West("West"),
    NorthWest("North West");

    private String value;

    DirectionsEnum(String value) {
        this.value = value;
    }

    public String getValue() {
        return value;
    }

    @Override
    public String toString() {
        return this.getValue();
    }

    public static DirectionsEnum getEnum(String value) {
        if(value == null)
            throw new IllegalArgumentException();
        for(DirectionsEnum v : values())
            if(value.equalsIgnoreCase(v.getValue())) return v;
        throw new IllegalArgumentException();
    }
}
Community
  • 1
  • 1
JAN
  • 21,236
  • 66
  • 181
  • 318