36

枚举是可比较的,这意味着您可以拥有

NavigableSet<AccessMode> modes = new TreeSet<>();
NavigableMap<AccessMode, Object> modeMap = new TreeMap<>();

这些有 O(ln N) 访问时间。

枚举集合具有 O(1) 访问时间,但不可导航

NavigableSet<AccessMode> modes = EnumSet.noneOf(AccessMode.class); // doesn't compile
NavigableMap<AccessMode, Object> modeMap = new EnumMap<>(AccessMode.class);  // doesn't compile

我想知道枚举集合是否不可导航(和排序)是否有原因。即我错过了什么吗?

4

3 回答 3

40

JDK 及其各种 API 缺少许多“明显”的特性。为什么这个特殊功能被忽略/忘记了?我们只能猜测。但是您的问题长期以来一直是 Sun/Oracle 的 RFE:

您可以通过评论来支持这些 RFE。请注意,这是 Joshua Bloch 关于该主题的权威回答:

我隐约记得考虑过它,但我不记得我们是否有充分的理由明确拒绝它。当我实现 EnumSet 和 EnumMap 时,我们的时间非常少,可能是时间在我们的决定中发挥了作用

http://comments.gmane.org/gmane.comp.java.jsr.166-concurrency/2158

所以即使也不得不猜测:-)

于 2012-07-19T09:05:03.840 回答
9

我最好的猜测是,可导航性并未被视为枚举集的主要用例。实现中没有任何东西会阻止导航性。TreeSet将一组枚举成员的需求与可导航性结合在一起的罕见用例TreeMap

于 2012-07-19T08:52:30.703 回答
2

The post doesn't directly answers the question, neither attempts to, it merely conveys why Navigable was introduced

Post as I was requested to (and it's too long for a comment)

The short answer is that Navigable exists because we didn't have anything like upcoming "defenders" -- Sorted didn't describe all the common functionality, and there was no way to do so except to introduce a new interface. In practice, I'm sure "Sorted" is still used much more often than "Navigable" as a declaration type, because most people don't need the methods defined in Navigable but not Sorted. Plus "Navigable" is just not a very nice name :-)

-Doug

于 2012-07-24T09:46:18.847 回答