枚举在Java中。优点? [英] Enum in Java. Advantages?
本文介绍了枚举在Java中。优点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
解决方案在Java中使用类似于类的枚举有什么优势,而不仅仅是C / C ++中的常量集合? div>
您可以免费编译时检查有效值。使用
public static int OPTION_ONE = 0;
public static int OPTION_TWO = 1;
不能确保
void selectOption(int option){
...
}
只能接受0或1作为参数值。使用枚举,这是有保证的。此外,这会导致更多的自我记录代码,因为您可以使用代码完成来查看所有枚举值。
What are some advantages of making enum in Java similar to a class, rather than just a collection of constants as in C/C++?
解决方案
You get free compile time checking of valid values. Using
public static int OPTION_ONE = 0;
public static int OPTION_TWO = 1;
does not ensure
void selectOption(int option) {
...
}
will only accept 0 or 1 as a parameter value. Using an enum, that is guaranteed. Moreover, this leads to more self documenting code, because you can use code completion to see all enum values.
这篇关于枚举在Java中。优点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文