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.
- Can you please explain why ignoring the documentation and always using
name()
is a bad idea? - What about the phrase "will not vary from release to release". If name will not vary, does it imply that
java.lang.Enum.toString()
would?