HashSet and TreeSet in Java

Both are present in java. util package.
Both evaluate on the basis of object values, not on the basis of the index.
Both cannot store any duplicate index.

HashSet is faster than TreeSet and it should be the preferred choice if sorting of the element is not required.

Difference:- HashSet store in random order whereas TreeSet store data in ascending order.

Elements in HashSet are not ordered. By using Comparable or Comparator method Tree set maintains the object in sorted order in Java. by default TreeSet elements are sorted in ascending order.

HashSet allows null object. TreeSet doesn’t allow null Object

Both of these classes are non-synchronized that means they are not thread-safe and they should be synchronized explicitly when there is a need for thread-safe operations.

import java.util.*;

public class HashSet_TreeSet_Ex 
{
	public static void main(String[] args) {
		HashSet<Integer> set1=new HashSet<Integer>();
		TreeSet<Integer> set2=new TreeSet<Integer>();
		int arr[]= {11,22,11,33,11,77,99};
		for(int a:arr)
		{
			set1.add(a);
			set2.add(a);
		}
		System.out.println(Arrays.toString(arr));
		System.out.println(set1);
		System.out.println(set2);
		System.out.println(set1.size());
		System.out.println(set2.size());
		System.out.println(set1.contains(99));
		set1.remove(99);
		System.out.println(set1);
		set2.remove(99);
		System.out.println(set2);

	}
}

Output:-
[11, 22, 11, 33, 11, 77, 99]
[33, 99, 22, 11, 77]
[11, 22, 33, 77, 99]
5
5
true
[33, 22, 11, 77]
[11, 22, 33, 77]
TreeSet and HashSet in Java
basicittopic

basicittopic

A Computer Science Study for IT students and people of IT community

Leave a Reply