您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Java 枚举是什么?它们为什么有用?

Java 枚举是什么?它们为什么有用?

当变量(尤其是方法参数)只能从一小部分可能的值中取出一个时,应始终使用枚举。例如类型常量(合同状态:“永久”,“临时”,“学徒”)或标志(“立即执行”,“推迟执行”)。

如果使用枚举而不是整数(或字符串代码),则将增加编译时检查并避免错误传入无效常量,并记录哪些值是合法使用的。

顺便说一句,枚举的过度使用可能意味着您的方法做得太多(通常最好有几个单独的方法,而不是一个带有几个修改功能的标志的方法),但是如果您必须使用标志或键入代码,则枚举是要走的路。

例如,哪个更好?

/** Counts number of foobangs.
 * @param type Type of foobangs to count. Can be 1=green foobangs,
 * 2=wrinkled foobangs, 3=sweet foobangs, 0=all types.
 * @return number of foobangs of type
 */
public int countFoobangs(int type)
与

/** Types of foobangs. */
public enum FB_TYPE {
 GREEN, WRINKLED, SWEET, 
 /** special type for all types combined */
 ALL;
}

/** Counts number of foobangs.
 * @param type Type of foobangs to count
 * @return number of foobangs of type
 */
public int countFoobangs(FB_TYPE type)

方法调用如下:

int sweetFoobangCount = countFoobangs(3);

然后变成:

int sweetFoobangCount = countFoobangs(FB_TYPE.SWEET);

在第二个示例中,可以立即清除允许哪些类型,文档和实现不能不同步,并且编译器可以强制执行此操作。另外,像

int sweetFoobangCount = countFoobangs(99);
java 2022/1/1 18:17:57 有424人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶