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:-
Performance:
HashSetprovides better performance thanTreeSetfor operations such asadd(),remove(),contains(), andsize().HashSetoffers an average time complexity of O(1) for these operations, whereasTreeSetprovides O(log n) time complexity.Internal Implementation:
HashSetis internally backed by aHashMap, whereasTreeSetis backed by aTreeMap.TreeMapuses a Red-Black Tree to store elements in sorted order.Ordering:
HashSetdoes not maintain any order of its elements. In contrast,TreeSetstores elements in their natural (ascending) order by default. BothHashSetandTreeSetdo not allow duplicate elements.Null Values:
HashSetallows onenullelement, whereasTreeSetdoes not allownullelements (when using natural ordering). Attempting to addnullto aTreeSetresults in aNullPointerExceptionbecause it internally uses thecompareTo()method (or aComparator) 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.
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