Organizational Research By

Surprising Reserch Topic

TreeSet Class in Java with example

TreeSet is similar to HashSet except that it sorts the elements in the ascending order while HashSet doesn’t maintain any order. TreeSet allows null element but like HashSet it doesn’t allow. Like most of the other collection classes this class is also not synchronized, however it can be synchronized explicitly like this: SortedSet s = Collections.synchronizedSortedSet(new TreeSet(...));

In this tutorial we are going to see TreeSet example and the difference between TreeSet and other similar collection classes.

TreeSet Example:

In this example we have two TreeSet (TreeSet & TreeSet). We have added the values to both of them randomly however the result we got is sorted in ascending order.

import java.util.TreeSet;
public class TreeSetExample {
     public static void main(String args[]) {
         // TreeSet of String Type
         TreeSet tset = new TreeSet();

         // Adding elements to TreeSet

         //Displaying TreeSet

         // TreeSet of Integer Type
         TreeSet tset2 = new TreeSet();

         // Adding elements to TreeSet
Output: You can see both the TreeSet have been sorted in ascending order implicitly.

[ABC, Ink, Jack, Pen, String, Test]
[0, 3, 7, 88, 101, 222]

asked Jun 11, 2015 in Java Interview Questions by rajesh
0 votes

Related Hot Questions

Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
Anti-spam verification:
To avoid this verification in future, please log in or register.