eagertoLearn
eagertoLearn

Reputation: 10142

Difference between NavigableSet, SortedSet and TreeSet in Java

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

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

Upvotes: 24

Views: 38809

Answers (5)

Asher A
Asher A

Reputation: 349

TreeSet implements NavigableSet, and (interface) NavigableSet extends SortedSet

Upvotes: 3

josh
josh

Reputation: 407

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.

Upvotes: 29

probalm
probalm

Reputation: 61

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

Upvotes: 3

MissingNumber
MissingNumber

Reputation: 1182

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

Upvotes: 3

ppawel
ppawel

Reputation: 1056

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.

Upvotes: 3

Related Questions