enum 对比Constants的好处(转载自:https://stackoverflow.com/a/26118954/1280694):
- Type safety and value safety.
- Guaranteed singleton.
- Ability to define and override methods.
- Ability to use values in
switch
statementcase
statements without qualification. - Built-in sequentialization of values via
ordinal().
- Serialization by name not by value, which offers a degree of future-proofing.
EnumSet
andEnumMap
classes.
转载自:https://stackoverflow.com/a/11575421/1280694
Suppose you use constant strings (or int
values - the same goes for them):
// Constants for player types
public static final String ARCHER = "Archer";
public static final String WARRIOR = "Warrior";
// Constants for genders
public static final String MALE = "Male";
public static final String FEMALE = "Female";
then you end up not really knowing the type of your data - leading to potentially incorrect code:
String playerType = Constants.MALE;
If you use enums, that would end up as:
// Compile-time error - incompatible types!
PlayerType playerType = Gender.MALE;
Likewise, enums give a restricted set of values:
String playerType = "Fred"; // Hang on, that's not one we know about...
vs
PlayerType playerType = "Fred"; // Nope, that doesn't work. Bang!
Additionally, enums in Java can have more information associated with them, and can also have behaviour. Much better all round.
Reference:
【1】:https://stackoverflow.com/questions/11575376/why-use-enums-instead-of-constants
【2】:https://stackoverflow.com/questions/3978654/best-way-to-create-enum-of-strings