为什么使用枚举,而不是常量?常量、而不是

2023-09-04 23:09:45 作者:野性领袖

我有一种情况中,我有播放器类型的射手,战士,和巫师。我应该在播放器类我用?类型或枚举一个字符串变量?为什么枚举,为什么常量字符串。请帮助的原因。

I have a scenario in which I have Player types ARCHER,WARRIOR, and sorcerer. What should I use in player class? A String variable for type or a Enum? Why enum and why Constant Strings. Please help with reasons.

推荐答案

假设你使用常量字符串(或 INT 值 - 这同样适用于他们):

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";

那么你最终没有真正了解你的数据的类型 - 导致潜在的不正确code:

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!

此外,在Java中枚举可以具有与它们相关联的详细信息,并且也可以有行为。好多全面。

Additionally, enums in Java can have more information associated with them, and can also have behaviour. Much better all round.