何时在 Java 中使用 Enum 或 Collection [英] When to use Enum or Collection in Java

查看:21
本文介绍了何时在 Java 中使用 Enum 或 Collection的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在什么情况下,枚举比保证唯一元素的 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.

这篇关于何时在 Java 中使用 Enum 或 Collection的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆