Java Design Pattern
Introduction to Java 10
Introduction to Java 11
Introduction to Java 12

JAVA TreeSet

TreeSet is an implementation class of Set interface.

Underlying data structure for TreeSet is Balanced Tree, that means when we create a TreeSet object internally a balanced tree will create for containing data items.

Duplicate data items are not allowed.

Insertion order is not preserved, but all data items are inserted according to some sorting order.

Heterogeneous data items are not allowed. If we are trying to insert heterogeneous objects then we will get runtime exception known as java.lang.ClassCastException.

Null insertion is allowed, but only once. If we will insert null in the middle then we will get java.lang.NullPointerException.


Constructors:

1. TreeSet( ) : Creates an empty TreeSet object where data items are inserted according to default natural sorting order, that is ascending order.

2. TreeSet(Comparator c) : Creates an empty TreeSet object where data items are inserted according to customized sorting order.

3. TreeSet t=new TreeSet(CollectionSet s) : From any Collection object, we can create an equivalent TreeSet object.


Let’s see the following examples:

TreeSetDemo1.java

import java.util.*;
class TreeSetDemo1
{
	public static void main(String[] args)
	{
		TreeSet t=new TreeSet();
		t.add(30);
		t.add(10);
		t.add(70);
		t.add(50);

		//t.add("java"); //java.lang.ClassCastException
		//t.add(null); //java.lang.NullPointerException

		System.out.println(t);
	}
}

Output :

img

Null Acceptance:

For the empty TreeSet as the first element null insertion is possible. But after inserting that null, if we are trying to insert any other element, we will get NullPointerException.

For non-empty TreeSet, if we are trying to insert null then we will get NullPointerException.

Let’s see another example:

TreeSetDemo2.java

import java.util.*;
class TreeSetDemo2
{
	public static void main(String[] args)
	{
		TreeSet t=new TreeSet();
		t.add(new StringBuffer("Odisha"));
		t.add(new StringBuffer("Mumbai"));
		t.add(new StringBuffer("Delhi"));
		System.out.println(t);
	}
}

Output :

img

About the Author



Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.


We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc






 PreviousNext