23
  • 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.

informatik01
  • 16,038
  • 10
  • 74
  • 104
eagertoLearn
  • 9,772
  • 23
  • 80
  • 122
  • check out the [docs](http://docs.oracle.com/javase/6/docs/api/java/util/NavigableSet.html), the NavigaleSet provides direct methods to get to the elements at the various location of the set. TreeSet is an implementation. – Bhesh Gurung Nov 06 '13 at 19:08
  • check this out : [docs](http://docs.oracle.com/javase/7/docs/api/java/util/Set.html) – Hussain Akhtar Wahid 'Ghouri' Nov 06 '13 at 19:09
  • The question is vaild because the all the implementations of SortedSet in the JDK also implement NavigableSet. So why does SortedSet exist as a separate interface? None of the answers here address this, and I am not aware of a data structure that would be able to implement SortedSet but not NavigableSet (although it may exist). – Stefan Reich Mar 01 '22 at 14:36

5 Answers5

27

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.

Android Killer
  • 18,174
  • 13
  • 67
  • 90
josh
  • 365
  • 3
  • 12
3

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.

ppawel
  • 1,046
  • 8
  • 17
3

TreeSet implements NavigableSet, and (interface) NavigableSet extends SortedSet

Community
  • 1
  • 1
Asher A
  • 327
  • 2
  • 3
2

I feel this is a well demonstrated reference with decent explanation.

MissingNumber
  • 1,142
  • 15
  • 29
2

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

probalm
  • 51
  • 3