Waq*_*qas 67 java enums android
我有一个场景,我有播放器类型ARCHER,WARRIOR和巫师.我应该在玩家类中使用什么?类型或枚举的String变量?为什么枚举和为什么Constant Strings.请帮助理由.
Jon*_*eet 119
假设您使用常量字符串(或int值 - 它们也是如此):
// 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";
Run Code Online (Sandbox Code Playgroud)
然后你最终不知道你的数据类型 - 导致可能不正确的代码:
String playerType = Constants.MALE;
Run Code Online (Sandbox Code Playgroud)
如果你使用枚举,最终会:
// Compile-time error - incompatible types!
PlayerType playerType = Gender.MALE;
Run Code Online (Sandbox Code Playgroud)
同样,枚举提供了一组受限制的值:
String playerType = "Fred"; // Hang on, that's not one we know about...
Run Code Online (Sandbox Code Playgroud)
VS
PlayerType playerType = "Fred"; // Nope, that doesn't work. Bang!
Run Code Online (Sandbox Code Playgroud)
此外,Java中的枚举可以包含与它们相关的更多信息,并且还可以具有行为.全面好多了.
除了不让你提供不正确的值之外,枚举的另一个特征可能看起来很小,但在我看来非常重要.现代IDE可以自动建议枚举值,而无法可靠地推断字符串常量的可能值(Intellij IDEA执行后者,但仅适用于JDK类和流行库).在您探索新API时,这尤其有用.
| 归档时间: |
|
| 查看次数: |
47781 次 |
| 最近记录: |