Collection Framework - SortedSet, NavigableSet and TreeSet

SortedSet is a interface that extends the Set interface.

As the name suggests, it contains certain methods specific to sorting. Duplicates not allowed, insertion order not preserved.

Elements are stored in a sorted manner. For integers, they are stored in ascending order. For Strings, its alphabetical order. Custom objects need to implement Comparable interface.

SortedSet has the following methods :

first() - returns first element
last() - returns last element
headSet(median) - returns elements before the median element
tailSet(median) - returns elements after the median element alongwith median element
subSet(startElement, lastElement) - set of elements inclusive startelement excluding lastElement
comparator() - returns comparator if you  have set a different rule for sorting. default null if you havent used any sorting.

Now we also need the facility to navigate through the elements, and for this NavigableSet was introduced. It extends the SortedSet and in addition brings the navigation methods :

lower(element) - returns the element less than the specified element
floor(element) - returns the element less than or equal to specified element
ceiling(element) - returns >= element to the specified element
higher(element) - returns > element to the specified element
pollFirst() - retreive and remove the first element
pollLast() - retreive and remove the last element

All the above methods return null if no such element found.

The implemention class is the TreeSet.
TreeSet is implemented based on underlying data structure as balanced tree. Objects are inserted based on a sorting order either natural or as specified. Since sorting is involved, we cannot have different types of elements stored. all elements should be of same type.

TreeSet has the following constructors :

TreeSet() - creates tree set with default sorting order
TreeSet(Comparator com) - creates tree set with sorting specifed by comparator
TreeSet(Collection coll) - creates tree set from collection with default sorting order
TreeSet(SortedSet set) - creates tree set from collection with sorting as per specified set

An example for TreeSet can be found here

Comments

Popular posts from this blog

Collection Framework - HashSet And LinkedHashSet class

Collection Framework - Cursors in Java

Hashed data structures