关于java:有没有任何理由EnumMap和EnumSet不可导航

Is there any reason EnumMap and EnumSet are not Navigable

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

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

它们有O(ln n)访问时间。

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

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

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


JDK及其各种API中缺少许多"明显"的特性。为什么省略/忘记了这个特殊功能?我们只能猜测。但您的问题在Sun/Oracle已经存在很长一段时间了:

  • http://bugs.sun.com/bugdatabase/view_bug.do?BugSyID=6278287
  • http://www.java.net/node/644910

您可以通过评论来支持这些RFE。请注意,下面是Joshua Bloch对这个问题的权威回答:

I vaguely recall considering it, but I can't recall whether we
explicitly rejected it with good reason. We were running very low on
time when I implemented EnumSet and EnumMap, and it's possible that
time played a role in our decision

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

所以即使是他也不得不猜测:—)


我的最佳猜测是navigability并没有被视为枚举集的主要用例。在实施过程中,没有任何东西会妨碍导航。TreeSetTreeMap涵盖了结合一组枚举成员和可导航性的罕见用例。


这篇文章并没有直接回答这个问题,也没有试图回答这个问题,它只是传达了为什么引入了可导航性。

按要求发帖(太长了,无法发表评论)

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