Java enums vs constants for Strings

Posted by Marcus on Stack Overflow See other posts from Stack Overflow or by Marcus
Published on 2010-03-14T01:59:08Z Indexed on 2010/03/14 2:05 UTC
Read the original article Hit count: 568

Filed under:
|
|

I've switched from using constants for Strings:

public static final String OPTION_1 = "OPTION_1";

... to enums:

public enum Options {
    OPTION_1;
}

With constants, you'd just refer to the constant:

  String s = TheClass.OPTION_1

But with Enums, you have to specify toString():

  String s = Options.OPTION_1.toString();

I don't like that you have to use the toString() statement, and also, in some cases you can forget to include it which can lead to unintended results.. ie:

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

Is there a better way to use enums for String constants?

© Stack Overflow or respective owner

Related posts about java

Related posts about enums