tags:

views:

411

answers:

2

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.

+3  A: 

There are a lot of good reasons to use Enum in Java. But not if you only need a String.

For example, if you are representing a specific set of entities and don't want them to be type-equivalent with other kinds of things (like Strings), then an Enum would be appropriate. Moreso if you are going to be calling functions that operate them and differentiate based on the particular instance.

On the other hand, if you are only interested in the String value of something, then there is nothing wrong with a String constant.

From what you've posted, I can't tell what the use case is. Is there some reason you need to use Enum here?

danben
+8  A: 

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.

In your snippet:

 Object o = map.get(Options.OPTION_1);
 //This won't work as intended if the Map key is a String

Compile-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>.

polygenelubricants