by, 11-13-2011 at 12:29 PM (1876 Views)
TreeSet belongs to Java Collection Framework and is very rare situations. In this post, I will briefly discuss when to use TreeSet and how to use it.
To use it, you have to import java.util.TreeSet in your class. TreeSet is not synchronized so if a TreeSet is concurrently accessed by threads then thread modifying the contents must be synchronized externally. TreeSet provides following constructors:
Since TreeSet is a type of Set, therefore duplicate values are not allowed. Also you cannot insert or fetch values from a particular index. Inserting and fetching value from an index is the property of Lists.
Ordering of elements in TreeSet is important. TreeSet maintains alphabetic order of elements in it.
Time for an example:
Output:Java Code:Vector vector = new Vector(); vector.add("String3"); vector.add("String1"); vector.add("String3"); Iterator it = vector.iterator(); while(it.hasNext()) System.out.println("Vector: " + it.next().toString()); TreeSet ts = new TreeSet(vector); it = ts.iterator(); while(it.hasNext()) System.out.println("TreeSet: " + it.next().toString());
The output is very interesting. It shows that TreeSet ignored duplicate values. Also TreeSet has ordered the elements in ascending order.
It is true to say that TreeSet is slower than HashSet and there is no tuning parameter for TreeSet. But still, TreeSet is a good choice in scenarios where you need a set with natural order.