Saturday, 5 October 2019

Difference Between HashSet and TreeSet in Java

        In this post, we will discuss the differences between HashSet and TreeSet in Java. Both HashSet and TreeSet implement the Set interface and do not allow duplicate elements. However, they differ in terms of ordering, performance, and internal implementation.

Difference between HashSet and TreeSet:-

  1. Performance: HashSet provides better performance than TreeSet for operations such as add(), remove(), contains(), and size(). HashSet offers an average time complexity of O(1) for these operations, whereas TreeSet provides O(log n) time complexity.

  2. Internal Implementation: HashSet is internally backed by a HashMap, whereas TreeSet is backed by a TreeMap. TreeMap uses a Red-Black Tree to store elements in sorted order.

  3. Ordering: HashSet does not maintain any order of its elements. In contrast, TreeSet stores elements in their natural (ascending) order by default. Both HashSet and TreeSet do not allow duplicate elements.

  4. Null Values: HashSet allows one null element, whereas TreeSet does not allow null elements (when using natural ordering). Attempting to add null to a TreeSet results in a NullPointerException because it internally uses the compareTo() method (or a Comparator) to compare elements.

Use a TreeSet when you need the elements to be stored in sorted order. If ordering is not required and performance is the primary concern, HashSet is the better choice.

HashSet and TreeSet examples:--

HashSetTreeSetExample.java
package com.example.demo;

import java.util.HashSet;
import java.util.TreeSet;

public class HashSetTreeSetExample {

       public static void main(String[] args) {

               HashSet<String> hashSet = new HashSet<String>();
               hashSet.add("Java");
               hashSet.add(".Net");
               hashSet.add("PHP");
               hashSet.add("Embedded C");

               System.out.println("HashSet elements are,");
               hashSet.stream().forEach(System.out::println);

               TreeSet<String> treeSet = new TreeSet<String>();
               treeSet.add("Java");
               treeSet.add(".Net");
               treeSet.add("PHP");
               treeSet.add("Embedded C");

               System.out.println("TreeSet elements are,");
               treeSet.stream().forEach(System.out::println);
       }
}

Output:--
HashSet elements are,
Java
Embedded C
.Net
PHP

TreeSet elements are,
.Net
Embedded C
Java
PHP


Thank you for visiting the blog.

No comments:

Post a Comment