TreeSet
puts an element in natural ordering or by the provided comparator.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.
TreeSet is sorted based on objects. TreeMap is sorted based on keys.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With