Home:ALL Converter>Java enums vs constants for Strings

Java enums vs constants for Strings

Ask Time:2010-03-14T09:59:08         Author:Marcus Leon

Json Formatter

I've switched from using constants for Strings to using enums. Many times I need the String representation of the enum (for logging, to pass to an API that requires a String, etc).

With String constants, you can just pass the String value, but with enums you have to call toString(). Is there a way you can "default" to the String value when supplying the enum variable?

As many posters have commented, perhaps one shouldn't be using enums if you frequently need the String representation.

Author:Marcus Leon,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/2440916/java-enums-vs-constants-for-strings
polygenelubricants :

You should fully adopt enum and not use the String representation in the first place. Only use the toString() to generate messages, logs, etc, but internally you'd want to work with enum. Any Map, Set, etc operations should be done on the enum type, which guarantees proper serialization, singleton pattern, and everything else that enum types are supposed to have.\n\nIn your snippet:\n\n Object o = map.get(Options.OPTION_1);\n //This won't work as intended if the Map key is a String\n\n\nCompile-time error aside, you should really question whether the map key should even be of type String in the first place. The way you're using it, it looks like it should be a Map<Options, Something>.",
2010-03-14T02:02:08
yy