Home » Core Java » TreeSet in Java

TreeSet in Java

TreeSet & its feature ::
1.  TreeSet class is an important class of Collection framework.
2.  TreeSet extends generic AbstractSet.
3.  TreeSet implements generic NavigableSet, cloneable and java.io.Serializable interface.
4.  TreeSet internally crates a TreeMap with initial size 0. TreeMap is a Red-Black tree based NavigableMap implementation.The map is sorted according to the Comparable natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used.TreeSet stores values in the key of the TreeMap.So TreeSet has always have unique elements stored.If you try to add duplicate element TreeSet replaces the old value with new value.
5.By default TreeSet stores the elements in natural sorting order and it gives unique elements.
6.  TreeSet is unsynchronized i.e. it is not thread safe.But, it can be made synchronized explicitly like below

7.TreeSet can accept any element excluding null values.If you try to add null values to TreeSet,you will get NullPointerException .
8. TreeSet implementation provides guaranteed log(n) time cost for the basic operations add(), remove() and contains().
9.TreeSet uses Iterator interface to traverse the elements.While traversing the elements using iterator if the structure of the TreeSet is modified using remove method ,iterator will throw ConcurrentModificationException.So iterators for TreeSet are fail-fast.While iterating you can add new elements without getting ConcurrentModificationException.

Sample Program ::

Output ::

Now let us see an example of ConcurrentModificationException.In the below program while iterating the TreeSet,i am modifying the structure of the TreeSet by removing an element.So I am getting ConcurrentModificationException.
Example of ConcurrentModificationException ::

Output ::

Leave a comment

Your email address will not be published. Required fields are marked *

1 × one =