View RSS Feed

My Java Tips

Using Treeset

Rate this Entry
by , 11-13-2011 at 11:29 AM (1309 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:
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:

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());
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.

Submit "Using Treeset" to Facebook Submit "Using Treeset" to Digg Submit "Using Treeset" to del.icio.us Submit "Using Treeset" to StumbleUpon Submit "Using Treeset" to Google

Comments