Saturday, 5 October 2019

Difference between HashSet and TreeSet in Java

        In the current post, we will see what are the differences between HashSet and TreeSet in Java. Both TreeSet and HashSet implements Set interface and doesn't contain duplicates.

Difference between HashSet and TreeSet:-

1) HashSet gives better performance compared to TreeSet for the operations like add, remove, contains, size etc. HashSet offers constant time cost while TreeSet offers log(n) time cost for such operations.

2) HashSet is implemented based on HashTable while TreeSet is implemented based on TreeMap. As we know that TreeMap uses a Red-Black algorithm to sort the elements.

3) HashSet does not maintain any order of elements while TreeSet elements are sorted by ascending order by default. Both HashSet and TreeSet doesn't contain duplicate elements.

4) HashSet allows null values but TreeSet doesn’t allow null values. If try to add null value in TreeSet will throw NullPointerException, because internally TreeSet uses compareTo() method to compare keys and compareTo() will throw NullPointerException.

     Use TreeSet if you need the inserted elements in sorted ascending order but performance wise HashSet is better.

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


Related Posts:--
1) Collection Hierarchy in Java
2) Collection Interview Questions and Answers in Java(List,Map & Set)
3) How to iterate the TreeMap in reverse order in Java
4) How to Remove duplicates from ArrayList in Java
5) Internal Implementation of TreeMap in Java
6) Internal implementation of ArrayList in Java
7) Internal Implementation of LinkedList in Java

No comments:

Post a comment