本文介绍了什么是枚举,为什么它们有用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天我正在浏览本网站上的一些问题,我发现提到了一个枚举 关于这种解决方案的线程安全利益。

Today I was browsing through some questions on this site and I found a mention of an enum being used in singleton pattern about purported thread safety benefits to such solution.

我从未使用过 enum s,而且我已经用Java编写了几年了。显然他们改变了很多。现在,他们甚至在自己的OOP中全力支持。

I have never used enums and I have been programing in Java for more than couple a years now. And apparently they changed a lot. Now they even do full blown support of OOP within themselves.

推荐答案

当变量(特别是方法参数)只能从一小组可能的值中取出一个时,应始终使用枚举。示例会是类型常量(合同状态:永久,临时,学徒)或标志(执行现在,推迟执行)。

You should always use enums when a variable (especially a method parameter) can only take one out of a small set of possible values. Examples would be things like type constants (contract status: "permanent", "temp", "apprentice"), or flags ("execute now", "defer execution").

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

If you use enums instead of integers (or String codes), you increase compile-time checking and avoid errors from passing in invalid constants, and you document which values are legal to use.

BTW,过度使用枚举可能意味着您的方法做得太多(通常最好有几个单独的方法,而不是一种方法,需要几个标志来修改它),但是如果你必须使用标志或类型代码,枚举是要走的路。

BTW, overuse of enums might mean that your methods do too much (it's often better to have several separate methods, rather than one method that takes several flags which modify what it does), but if you have to use flags or type codes, enums are the way to go.

作为一个例子,哪个更好?

As an example, which is better?

/** 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);






在第二个例子中,是允许的,文档和实现不能不同步,编译器可以强制执行。
另外,一个无效的调用,如


In the second example, it's immediately clear which types are allowed, docs and implementation cannot go out of sync, and the compiler can enforce this.Also, an invalid call like

int sweetFoobangCount = countFoobangs(99);

不再可能。

这篇关于什么是枚举,为什么它们有用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 02:45