TreeSet, LinkedHashSet together with HashSet all are implementation of Set interface together with yesteryear virtue of that, they follows contract of Set interface i.e. they exercise non allow duplicate elements. Despite beingness from same type hierarchy, at that topographic point are lot of divergence betwixt them; which is of import to understand, thence that you lot tin lead most appropriate Set implementation based upon your requirement. By the way divergence betwixt TreeSet together with HashSet or LinkedHashSet is likewise 1 of the popular Java Collection interview question, non equally pop equally Hashtable vs HashMap or ArrayList vs Vector but all the same appears inward diverse Java interviews. In this article nosotros volition come across difference betwixt HashSet, TreeSet together with LinkedHashSet on diverse points e.g. Ordering of elements, performance, allowing nix etc together with thence nosotros volition come across When to utilization TreeSet or LinkedHashSet or simply HashSet inward Java.
Difference betwixt TreeSet, LinkedHashSet together with HashSet inward Java
TreeSet, LinkedHashSet together with HashSet inward Java are iii Set implementation inward collection framework together with similar many others they are likewise used to shop objects. Main characteristic of TreeSet is sorting, LinkedHashSet is insertion social club together with HashSet is only full general role collection for storing object. HashSet is implemented using HashMap inward Java piece TreeSet is implemented using TreeMap. TreeSet is a SortedSet implementation which allows it to overstep along elements inward the sorted social club defined yesteryear either Comparable or Comparator interface. Comparable is used for natural social club sorting together with Comparator for custom social club sorting of objects, which tin hold out provided piece creating instance of TreeSet. Anyway before seeing divergence betwixt TreeSet, LinkedHashSet together with HashSet, let's come across around similarities betwixt them:
1) Duplicates : All iii implements Set interface agency they are non allowed to shop duplicates.
2) Thread security : HashSet, TreeSet together with LinkedHashSet are non thread-safe, if you utilization them inward multi-threading environs where at to the lowest degree 1 Thread modifies Set you lot ask to externally synchronize them.
3) Fail-Fast Iterator : Iterator returned yesteryear TreeSet, LinkedHashSet together with HashSet are fail-fast Iterator. i.e. If Iterator is modified afterward its creation yesteryear whatever way other than Iterators remove() method, it volition throw ConcurrentModificationException alongside best of effort. read to a greater extent than about fail-fast vs fail-safe Iterator here
Now let’s come across difference betwixt HashSet, LinkedHashSet together with TreeSet inward Java :
Performance together with Speed : First divergence betwixt them comes inward price of speed. HashSet is fastest, LinkedHashSet is 2nd on performance or virtually similar to HashSet but TreeSet is chip slower because of sorting functioning it needs to perform on each insertion. TreeSet provides guaranteed O(log(n)) fourth dimension for mutual operations similar add, take away together with contains, piece HashSet together with LinkedHashSet offering constant fourth dimension performance e.g. O(1) for add, contains together with take away given hash business office uniformly distribute elements inward bucket.
Ordering : HashSet does non hold whatever social club piece LinkedHashSet maintains insertion social club of elements much similar List interface together with TreeSet maintains sorting social club or elements.
Internal Implementation : HashSet is backed yesteryear an HashMap instance, LinkedHashSet is implemented using HashSet together with LinkedList piece TreeSet is backed upwardly yesteryear NavigableMap inward Java together with yesteryear default it uses TreeMap.
null : Both HashSet together with LinkedHashSet allows nix but TreeSet doesn't allow nix but TreeSet doesn't allow nix together with throw java.lang.NullPointerException when you lot volition insert nix into TreeSet. Since TreeSet uses compareTo() method of respective elements to compare them which throws NullPointerException piece comparing alongside null, hither is an example:
TreeSet cities
Exception inward thread "main" java.lang.NullPointerException
at java.lang.String.compareTo(String.java:1167)
at java.lang.String.compareTo(String.java:92)
at java.util.TreeMap.put(TreeMap.java:545)
at java.util.TreeSet.add(TreeSet.java:238)
Comparison : HashSet together with LinkedHashSet uses equals() method inward Java for comparing but TreeSet uses compareTo() method for maintaining ordering. That's why compareTo() should hold out consistent to equals inward Java. failing to exercise thence interruption full general contact of Set interface i.e. it tin permit duplicates.
TreeSet vs HashSet vs LinkedHashSet - Example
Let’s compare all these Set implementation on around points yesteryear writing Java program. In this instance nosotros are demonstrating divergence inward ordering, fourth dimension taking piece inserting 1M records amid TreeSet, HashSet together with LinkedHashSet inward Java. This volition attention to solidify around points which discussed inward before department together with attention to create upwardly one's hear when to utilization HashSet, LinkedHashSet or TreeSet inward Java.
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.TreeSet;
/**
* Java programme to demonstrate divergence betwixt TreeSet, HashSet together with LinkedHashSet
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.TreeSet;
/**
* Java programme to demonstrate divergence betwixt TreeSet, HashSet together with LinkedHashSet
* inward Java Collection.
* @author
*/
public class SetComparision {
public static void main(String args[]){
HashSet<String> fruitsStore = new HashSet<String>();
LinkedHashSet<String> fruitMarket = new LinkedHashSet<String>();
TreeSet<String> fruitBuzz = new TreeSet<String>();
for(String fruit: Arrays.asList("mango", "apple", "banana")){
fruitsStore.add(fruit);
fruitMarket.add(fruit);
fruitBuzz.add(fruit);
}
* @author
*/
public class SetComparision {
public static void main(String args[]){
HashSet<String> fruitsStore = new HashSet<String>();
LinkedHashSet<String> fruitMarket = new LinkedHashSet<String>();
TreeSet<String> fruitBuzz = new TreeSet<String>();
for(String fruit: Arrays.asList("mango", "apple", "banana")){
fruitsStore.add(fruit);
fruitMarket.add(fruit);
fruitBuzz.add(fruit);
}
//no ordering inward HashSet – elements stored inward random order
System.out.println("Ordering inward HashSet :" + fruitsStore);
System.out.println("Ordering inward HashSet :" + fruitsStore);
//insertion social club or elements – LinkedHashSet storeds elements equally insertion
System.err.println("Order of chemical factor inward LinkedHashSet :" + fruitMarket);
System.err.println("Order of chemical factor inward LinkedHashSet :" + fruitMarket);
//should hold out sorted social club – TreeSet stores chemical factor inward sorted social club
System.out.println("Order of objects inward TreeSet :" + fruitBuzz);
System.out.println("Order of objects inward TreeSet :" + fruitBuzz);
//Performance attempt to insert 10M elements inward HashSet, LinkedHashSet together with TreeSet
Set<Integer> numbers = new HashSet<Integer>();
long startTime = System.nanoTime();
for(int i =0; i<10000000; i++){
numbers.add(i);
}
Set<Integer> numbers = new HashSet<Integer>();
long startTime = System.nanoTime();
for(int i =0; i<10000000; i++){
numbers.add(i);
}
long endTime = System.nanoTime();
System.out.println("Total fourth dimension to insert 10M elements inward HashSet inward s : "
+ (endTime - startTime));
// LinkedHashSet performance Test – inserting 10M objects
// LinkedHashSet performance Test – inserting 10M objects
numbers = new LinkedHashSet<Integer>();
startTime = System.nanoTime();
for(int i =0; i<10000000; i++){
numbers.add(i);
}
endTime = System.nanoTime();
System.out.println("Total fourth dimension to insert 10M elements inward LinkedHashSet inward s : "
startTime = System.nanoTime();
for(int i =0; i<10000000; i++){
numbers.add(i);
}
endTime = System.nanoTime();
System.out.println("Total fourth dimension to insert 10M elements inward LinkedHashSet inward s : "
+ (endTime - startTime));
// TreeSet performance Test – inserting 10M objects
numbers = new TreeSet<Integer>();
startTime = System.nanoTime();
for(int i =0; i<10000000; i++){
numbers.add(i);
}
endTime = System.nanoTime();
System.out.println("Total fourth dimension to insert 10M elements inward TreeSet inward s : "
numbers = new TreeSet<Integer>();
startTime = System.nanoTime();
for(int i =0; i<10000000; i++){
numbers.add(i);
}
endTime = System.nanoTime();
System.out.println("Total fourth dimension to insert 10M elements inward TreeSet inward s : "
+ (endTime - startTime));
}
}
Output
Ordering inward HashSet :[banana, apple, mango]
Order of chemical factor inward LinkedHashSet :[mango, apple, banana]
Order of objects inward TreeSet :[apple, banana, mango]
Total fourth dimension to insert 10M elements inward HashSet inward s : 3564570637
Total fourth dimension to insert 10M elements inward LinkedHashSet inward s : 3511277551
Total fourth dimension to insert 10M elements inward TreeSet inward s : 10968043705
}
}
Output
Ordering inward HashSet :[banana, apple, mango]
Order of chemical factor inward LinkedHashSet :[mango, apple, banana]
Order of objects inward TreeSet :[apple, banana, mango]
Total fourth dimension to insert 10M elements inward HashSet inward s : 3564570637
Total fourth dimension to insert 10M elements inward LinkedHashSet inward s : 3511277551
Total fourth dimension to insert 10M elements inward TreeSet inward s : 10968043705
When to utilization HashSet, TreeSet together with LinkedHashSet inward Java
Since all iii implements Set interface they tin be used for mutual Set operations similar non allowing duplicates but since HashSet, TreeSet together with LinkedHashSet has at that topographic point especial characteristic which makes them appropriate inward sure enough scenario. Because of sorting social club provided yesteryear TreeSet, utilization TreeSet when you lot ask a collection where elements are sorted without duplicates. HashSet are rather full general role Set implementation, Use it equally default Set implementation if you lot ask a fast, duplicate gratis collection. LinkedHashSet is extension of HashSet together with its to a greater extent than suitable where you lot ask to hold insertion order of elements, similar to List without compromising performance for costly TreeSet. Another utilization of LinkedHashSet is for creating copies of existing Set, Since LinkedHashSet preservers insertion order, it returns Set which contains same elements inward same social club similar exact copy. In short, although all iii are Set interface implementation they offering distinctive feature, HashSet is a full general role Set piece LinkedHashSet provides insertion social club guarantee together with TreeSet is a SortedSet which stores elements inward sorted social club specified yesteryear Comparator or Comparable inward Java.
How to re-create object from 1 Set to other
Here is code instance of LinkedHashSet which demonstrate How LinkedHashSet tin hold out used to re-create objects from 1 Set to around other without losing order. You volition instruct exact replica of rootage Set, inward price of contents together with order. Here static method copy(Set source) is written using Generics, This form of parameterized method provides type-safety together with attention to avoid ClassCastException at runtime.
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;
/**
* Java programme to copy object from 1 HashSet to around other using LinkedHashSet.
* LinkedHashSet preserves social club of chemical factor piece copying elements.
*
* @author Javin
*/
public class SetUtils{
public static void main(String args[]) {
HashSet<String> rootage = new HashSet<String>(Arrays.asList("Set, List, Map"));
System.out.println("source : " + source);
Set<String> re-create = SetUtils.copy(source);
System.out.println("copy of HashSet using LinkedHashSet: " + copy);
}
/*
* Static utility method to re-create Set inward Java
*/
public static <T> Set<T> copy(Set<T> source){
return new LinkedHashSet<T>(source);
}
}
Output:
rootage : [Set, List, Map]
re-create of HashSet using LinkedHashSet: [Set, List, Map]
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;
/**
* Java programme to copy object from 1 HashSet to around other using LinkedHashSet.
* LinkedHashSet preserves social club of chemical factor piece copying elements.
*
* @author Javin
*/
public class SetUtils{
public static void main(String args[]) {
HashSet<String> rootage = new HashSet<String>(Arrays.asList("Set, List, Map"));
System.out.println("source : " + source);
Set<String> re-create = SetUtils.copy(source);
System.out.println("copy of HashSet using LinkedHashSet: " + copy);
}
/*
* Static utility method to re-create Set inward Java
*/
public static <T> Set<T> copy(Set<T> source){
return new LinkedHashSet<T>(source);
}
}
Output:
rootage : [Set, List, Map]
re-create of HashSet using LinkedHashSet: [Set, List, Map]
Always code for interface than implementation thence that you lot tin supersede HashSet to LinkedHashSet or TreeSet when your requirement changes. That’s all on difference betwixt HashSet, LinkedHashSet together with TreeSet inward Java. If you lot know whatever other pregnant divergence betwixt TreeSet, LinkedHashSet together with HashSet which is worth remembering than delight add together equally comment.
Further Learning
Java In-Depth: Become a Complete Java Engineer
How to sort ArrayList inward descending social club inward Java