何时在 Java 中使用 Enum 或 Collection

2022-01-17 00:00:00 set enums java

在什么情况下,枚举比保证唯一元素的 Collection(我猜是 java.util.Set 的实现者……)更合适?

Under what circumstances is an enum more appropriate than, for example, a Collection that guarantees unique elements (an implementer of java.util.Set, I guess...)?

(这是我之前的 问题)

推荐答案

基本上当它是一个定义明确的、在编译时已知的固定值集时.

Basically when it's a well-defined, fixed set of values which are known at compile-time.

您可以非常轻松地将枚举用作集合(使用 EnumSet),它允许您定义行为、按名称引用元素、打开它们等.

You can use an enum as a set very easily (with EnumSet) and it allows you to define behaviour, reference the elements by name, switch on them etc.

相关文章