TreeSet Class in Collection Framework

java.util.TreeSet;
public class TreeSet extends AbstractSet implements NavigableSet, Cloneable, java.io.Serializable
TreeSet provides an implementation of the Set interface that uses a tree for storage and guarantees that the elements will be in ascending order, according to natural order. Access and retrieval times are quite fast, which makes TreeSet an excellent choice when storing large amounts of sorted information that must be found quickly.
TreeSet class features:
  1. It is an insertion ordered, sorted set.
  2. It can not contain duplicate elements.
  3. It is unsynchronized.
  4. A TreeSet can contain at most one null value.
  5. compareTo() and equals() methods is used for its elements .
  6. Data structure is based on Balanced tree.
To prevent unsynchronized access to the list:
SortedSet set = Collections.synchronizedSet(new TreeSet(…));
Constructor of TreeSet
  1. public TreeSet ()
    It is used to create a new, empty tree set, sorted according to the natural ordering of its elements.
  2. public TreeSet(Collection c)
              it is used to create a new tree set containing the elements in the specified collection, sorted according to the natural ordering of its elements.
  3. public TreeSet(Comparator comp )
             it is used to create a new, empty tree set, sorted according to the specified comparator.
  4. public TreeSet(SortedSet ss)
             it is used to create a new tree set containing the same elements and using the same ordering as the specified sorted set.
Example of TreeSet class
import java.util.TreeSet; import java.util.Iterator; public class TreeSetDemo{ public static void main(String[] args) { // TreeSet Creation TreeSet ts = new TreeSet(); // Adding elements to the TreeSet ts.add("101"); ts.add("102"); ts.add("106"); ts.add("101"); ts.add("104"); ts.add("105"); ts.add("108"); ts.add("106"); // Display content of TreeSet System.out.println("Content of ts " + ts); // Display content of TreeSet using iterator Iterator it=ts.iterator(); System.out.println("Content of TreeSet using iterator() : "); while(it.hasNext()) { System.out.println(it.next()); } } }
Output

Content of ts [101, 102, 104, 105, 106, 108]
Content of TreeSet using iterator() :
101
102
104
105
106
108

Download this example
 



 

Latest Tutorial


Most Visited Tutorial