Java 中不可修改的 NavigableSet/NavigableMap?
java.util.Collections 有几个不可修改的方法,它们通过将集合包装在禁止突变操作的装饰器中来提供不可修改的集合视图。
Java 6 添加了对 java.util.NavigableSet 和 java.util.NavigableMap 的支持。
我希望能够拥有不可修改的 NavigableSet
和 NavigableMap
,但是 java.util.Collections#unmodifyingSortedSet(SortedSet)
和 < code>java.util.Collections#unmodifyingSortedMap(SortedMap) 是不够的,因为它们不支持 NavigableSet
和 NavigableMap
特有的操作。
unmodifyingNavigableSet
和 unmodifyingNavigableMap
是否有事实上的实现?
java.util.Collections
has several unmodifiable
methods that provide unmodifiable collection views by wrapping collections in decorators that prohibit mutation operations.
Java 6 added support for java.util.NavigableSet
and java.util.NavigableMap
.
I'd like to be able to have unmodifiable NavigableSet
s and NavigableMap
s, but java.util.Collections#unmodifiableSortedSet(SortedSet)
and java.util.Collections#unmodifiableSortedMap(SortedMap)
are not sufficient because they do not support the operations that are particular to NavigableSet
and NavigableMap
.
Are there de-facto implementations for unmodifiableNavigableSet
and unmodifiableNavigableMap
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Guava 现在提供(自 12.0 版本起,2012 年 4 月 30 日发布)Maps.unmodifyingNavigableMap 和 Sets.unmodifyingNavigableSet。
Guava now provides (since version 12.0, released April 30, 2012) Maps.unmodifiableNavigableMap and Sets.unmodifiableNavigableSet.
Java SE 8 包含这两种方法。
请参阅 Javadoc< /a>.
Java SE 8 included these two methods.
See the Javadoc.
这只是一个猜测,但未提供不可修改的实现的部分原因可能是由于 NavigableSet/Map 接口公开了未标记为可选的变异方法:
也就是说,在提供不可修改的实现时仅抛出 UnsupportedOperationException 似乎是合理的。这就是这些实现中所做的事情(假设您使用的是 GoogleGuava):
NavigableSet:
导航地图:
This is just a guess, but part of the reason why an unmodifiable implementation was not provided may be due to the fact that the NavigableSet/Map interfaces expose mutating methods that aren't marked as optional:
That said, it seems reasonable when providing an unmodifiable implementation to just throw an UnsupportedOperationException. That is what is done in these implementations (which assume you're using GoogleGuava):
NavigableSet:
NavigableMap:
来自 Christian Semrau(在问题评论中):
JDK 中没有这样的方法,如 此错误报告。
From Christian Semrau (in the question comments):
There are no such methods within the JDK, as mentioned in this bug report.