Java enum - why use toString instead of name

后端 未结 7 2062
清酒与你
清酒与你 2020-11-28 22:18

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.

7条回答
  •  抹茶落季
    2020-11-28 22:56

    Use name() when you want to make a comparison or use the hardcoded value for some internal use in your code.

    Use toString() when you want to present information to a user (including a developper 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.

    From the javadoc (emphasis mine) :

    Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.

提交回复
热议问题