views:

188

answers:

2

I am trying to add more user friendly descriptions for multiple enum members in the same class. Right now I just have each enum returned in lowercase:

public enum Part {
    ROTOR, DOUBLE_SWITCH, 100_BULB, 75_BULB, 
    SMALL_GAUGE, LARGE_GAUGE, DRIVER;

    private final String description;

    Part() {
      description = toString().toLowerCase();
    }

    Part(String description) {
      this.description = description;
    }

    public String getDescription() {
      return description;
    }
}

Is there a way to give each enum value a more user-friendly name which I can display via the toString() for each Part member? For example when I interate over the Parts:

for (Part part : Part.values()) {
System.out.println(part.toString());
}

rather than getting the literal list:

ROTOR
DOUBLE_SWITCH
100_BULB
75_BULB 
SMALL_GAUGE
LARGE_GAUGE
DRIVER

I am hoping to give meaningful descriptions to each item so I can output something like:

Standard Rotor
Double Switch
100 W bulb
75 W bulb 
Small Gauge
Large Gauge
Torque Driver

So I was wondering if there is a way to give those meaningful descriptions for each enum member in my Part enum class.

Many thanks

+6  A: 

Enums are really classes in disguise, forced to be a single instance. You can do something like this below to give each a name. You can give it any number of proprties you like in the constructor. It doesn't affect how you reference it. In the example below, ROTOR will have a string representation of "This is a rotor".

public enum Part {
  ROTOR("This is a rotor");

  private final String name;

  Part(final String name) {
      this.name = name;
  } 

  @Override
  public String toString() {
      return name;
  }
}
Jeff Foster
A: 

Yes, you already have a constructor that takes a description. Why not use that?

public enum Part { ROTOR("Rotor"), DOUBLE_SWITCH("Double Switch"), 100_BULB, 75_BULB, SMALL_GAUGE, LARGE_GAUGE, DRIVER;

private final String description;

Part() {
  description = toString().toLowerCase();
}

Part(String description) {
  this.description = description;
}

public String getDescription() {
  return description;
}
}
Jeff Storey
Thanks for both answers. that's what I was looking for
denchr