Using TreeSet
10 December 2007TreeSet 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:
TreeSet()
TreeSet(Collection c)
TreeSet(Comparator c)
TreeSet(SortedSet s)
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:
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());
Output:
Vector: String3 Vector: String1 Vector: String3 TreeSet: String1 TreeSet: String3
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.
Related Posts:
Top Of Page | Trackback
If you found this page useful, consider linking to it. Simply copy and paste the code below into your web site.
It will look like this: Using TreeSet
I find the TreeSet very very useful. The only fact is to know that you need either a Comparator or the elements must implement Comparable. The performance isn’t quite different from the HashSet for medium sizes.