Java 中 NavigableSet、SortedSet 和 TreeSet 的区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19820562/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 20:28:25  来源:igfitidea点击:

Difference between NavigableSet, SortedSet and TreeSet in Java

javasettreesetsortedset

提问by eagertoLearn

  • A TreeSetputs an element in natural orderingor by the provided comparator.
  • A SortedSetis also keeps the element in natural order
  • ATreeSet将元素按自然顺序排列或按提供的 比较器排列
  • ASortedSet也使元素保持自然顺序

But what is the difference between them and NavigableSet?
Where are NavigableSetsuseful?

但是它们之间有什么区别和NavigableSet?
哪里NavigableSets有用?

Some example to show its usage would be nice for beginners.

一些显示其用法的示例对初学者来说会很好。

回答by ppawel

I hope you will find useful the following excerpt from Java docs(see link to more details):

我希望您会发现以下Java 文档摘录很有用(请参阅更多详细信息的链接):

Methods lower, floor, ceiling, and higherreturn elements respectively less than, less than or equal, greater than or equal, and greater than a given element.

方法lowerfloorceilinghigher分别返回小于、小于等于、大于等于、大于给定元素的元素。

回答by MissingNumber

I feel thisis a well demonstrated reference with decent explanation.

我觉得这this是一个很好的参考,有很好的解释。

回答by josh

SortedSet is an interface (it defines the functionality) and Treeset is an implementation. NavigableSet is also an interface subtype of the SortedSet.

SortedSet 是一个接口(它定义了功能),而 Treeset 是一个实现。NavigableSet 也是 SortedSet 的接口子类型。

You can't just write SortedSet<Integer> example = new SortedSet<Integer>();

你不能只写 SortedSet<Integer> example = new SortedSet<Integer>();

You can however write SortedSet<Integer> example = new TreeSet<Integer>();

但是你可以写 SortedSet<Integer> example = new TreeSet<Integer>();

As its name implies, NavigableSets are more useful for navigating through the set.

顾名思义,NavigableSets 对于在集合中导航更有用。

http://mrbool.com/overview-on-navigableset-subtype-of-java-collections/25417offers a good tutorial on NavigableSets and some of the methods available when using one, that aren't available in a SortedSet.

http://mrbool.com/overview-on-navigableset-subtype-of-java-collections/25417提供了一个关于 NavigableSets 的很好的教程和一些使用时可用的方法,这些方法在 SortedSet 中不可用。

回答by probalm

NavigableSet adds Navigation methods like descendingIterator() and descendingSet(), ceiling(), floor(), higher(), lower(), headSet(), tailSet(), subSet(), pollFirst() and pollLast().

NavigableSet 添加了诸如descendingIterator() 和descendingSet()、ceiling()、floor()、higher()、lower()、headSet()、tailSet()、subSet()、pollFirst() 和 pollLast() 等导航方法。

回答by Asher A

TreeSet implements NavigableSet, and (interface) NavigableSet extends SortedSet

TreeSet 实现了 NavigableSet,并且(接口)NavigableSet 扩展了 SortedSet