After reading the documentation of String java.lang.Enum.name()
I am not sure I understand when to use name() and when to use toString().
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.
In particular, even though the documentation says to prefer toString()
, Java's own StandardLocation enumeration uses name
when I would have thought the documentation suggested otherwise.
public String getName() { return name(); }
Furthermore Enum
implements toString()
as,
public String toString() {
return name;
}
and I cannot think of a situation where a user defined enumeration would overwrite toString()
so name()
and toString()
are almost always exactly the same.
name()
is a bad idea?java.lang.Enum.toString()
would?Use toString() when you want to present information to a user (including a developer looking at a log). Never rely in your code on toString()
giving a specific value. Never test it against a specific string. If your code breaks when someone correctly changes the toString()
return, then it was already broken.
If you need to get the exact name used to declare the enum constant, you should use name() as toString
may have been overridden.
Use toString
when you need to display the name to the user.
Use name
when you need the name for your program itself, e.g. to identify and differentiate between different enum values.
Source: Stackoverflow.com