Java enum - why use toString instead of name

spauny picture spauny · Nov 8, 2012 · Viewed 183.2k times · Source

If you look in the enum api at the method name() it says that:

Returns the name of this enum constant, exactly as declared in its enum declaration. Most programmers should use the toString method in preference to this one, as the toString method may return a more user-friendly name. This method is designed primarily for use in specialized situations where correctness depends on getting the exact name, which will not vary from release to release.

Why is better to use toString()? I mean toString may be overridden when name() is already final. So if you use toString and someone overrides it to return a hard-coded value your whole application is down... Also if you look in the sources the toString() method returns exactly and just the name. It's the same thing.

Answer

assylias picture assylias · Nov 8, 2012

It really depends on what you want to do with the returned value:

  • If you need to get the exact name used to declare the enum constant, you should use name() as toString may have been overriden
  • If you want to print the enum constant in a user friendly way, you should use toString which may have been overriden (or not!).

When I feel that it might be confusing, I provide a more specific getXXX method, for example:

public enum Fields {
    LAST_NAME("Last Name"), FIRST_NAME("First Name");

    private final String fieldDescription;

    private Fields(String value) {
        fieldDescription = value;
    }

    public String getFieldDescription() {
        return fieldDescription;
    }
}