简体   繁体   中英

Difference between NavigableSet, SortedSet and TreeSet in Java

  • A TreeSet puts an element in natural ordering or by the provided comparator .
  • A SortedSet is also keeps the element in natural order

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

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

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

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

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

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

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

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

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

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

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

TreeSet实现了NavigableSet,而(interface)NavigableSet扩展了SortedSet

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM