What is TreeSet

What is TreeSet

Answer: In Java TreeSet is a class which extends AbstractSet implements NavigableSet interface. It uses tree for storage of collection. Be default elements in ascending, sorted order. TreeSet is excellent choice for storing large amount of information because retrieval time is very fast.

TreeSet is generic class below is descriptioin:
class TreeSet<E>

Where, E is generic and it denotes type of objects that will be stored.

TreeSet constructors:

  • TreeSet( ) – It uses default sorting i.e. ascending order of the elements
  • TreeSet(Collection<? extends E> c) – This build tree set that will be containing element of c
  • TreeSet(Comparator<? super E> comp) – In this constructor Comparator parameter has been passed so that element will be sorted based on comparator ascending or descending order logic.
  • TreeSet(SortedSet ss) – This build tree set that will be containing element of ss

Below is example of TreeSet:

package com.javahonk.hashsettest;

import java.util.TreeSet;

public class TreeSetTest {

	public static void main(String args[]) {
	// Create a tree set.
	TreeSet<String> ts = new TreeSet<String>();
	// Add elements
	System.out.println("Please note it keeps "
			+ "element in sorted order");




What is TreeSet


Leave a Reply

Your email address will not be published. Required fields are marked *

I am not Robot *