Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between NavigableSet, SortedSet and TreeSet in Java

Tags:

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

like image 405
eagertoLearn Avatar asked Nov 06 '13 19:11

eagertoLearn


People also ask

What is the difference between NavigableSet and SortedSet in Java?

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

What is the difference between TreeMap and TreeSet in Java?

TreeSet is sorted based on objects. TreeMap is sorted based on keys.

What is difference between TreeSet and HashSet in Java?

Hash set and tree set both belong to the collection framework. HashSet is the implementation of the Set interface whereas Tree set implements sorted set. Tree set is backed by TreeMap while HashSet is backed by a hashmap. Sr.

What is NavigableSet in Java?

NavigableSet represents a navigable set in Java Collection Framework. The NavigableSet interface inherits from the SortedSet interface. It behaves like a SortedSet with the exception that we have navigation methods available in addition to the sorting mechanisms of the SortedSet.


2 Answers

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.

like image 75
josh Avatar answered Sep 18 '22 15:09

josh


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.

like image 32
ppawel Avatar answered Sep 16 '22 15:09

ppawel