implementation of the Set interface and by advantage of that, they comply with the contract of Set interface i.e. they don’t enable duplicate parts.
Regardless of being from the identical sort of hierarchy, there are numerous variations between them;
which is necessary to know, with the intention to select probably the most appropriate Set implementation based mostly upon
your requirement. By the best way distinction between TreeSet and HashSet or LinkedHashSet can also be
one of many common Java Assortment interview questions, not as common as Hashtable vs HashMap or ArrayList vs Vector however nonetheless
seems in varied Java interviews.
On this article, we are going to see the distinction between HashSet, TreeSet, and LinkedHashSet on varied factors e.g. Ordering of parts,
efficiency, permitting null, and many others after which we are going to see When to make use of TreeSet or LinkedHashSet or ssuggest HashSet
in Java.
Distinction between TreeSet, LinkedHashSet, and HashSet in Java
are three Set implementations within the assortment framework and like many others they
are additionally used to retailer objects. The primary characteristic of TreeSet is
sorting, LinkedHashSet is
insertion order and HashSet is simply normal goal
assortment for storing objects.
HashSet is carried out using HashMap in Java whereas TreeSet
is carried out utilizing TreeMap. TreeSet is a SortedSet
implementation that enables it to maintain parts within the sorted order outlined by
both Comparable or Comparator interface.
Comparable is used for pure order sorting and Comparator for customized order sorting of
objects, which will be offered whereas creating an occasion of TreeSet.
Anyway earlier than seeing
distinction between TreeSet, LinkedHashSet, and HashSet, let’s have a look at
some similarities between them:
1) Duplicates: All three implements Set interface means they’re
not allowed to retailer duplicates.
2) Thread security: HashSet, TreeSet and LinkedHashSet are not thread-safe, if you use them
in multi-threading atmosphere the place at the very least one Thread modifies Set you must externally synchronize them.
Iterator is modified after its creation by any means apart from Iterators take away() methodology, it
will throw ConcurrentModificationException with greatest
of effort. learn extra about fail-fast vs fail-safe Iterator
here
Now let’s see the distinction between HashSet, LinkedHashSet, and TreeSet in
Java :
1. Efficiency and Velocity
The primary distinction between them comes when it comes to pace. HashSet is
quickest, LinkedHashSet is second on efficiency or
nearly much like HashSet however TreeSet is a bit
slower due to the sorting operation it must carry out on every insertion. TreeSet offers
assured O(log(n)) time for frequent operations like
add, take away, and accommodates, whereas HashSet and LinkedHashSet supply
constant-time efficiency e.g. O(1) for add, accommodates, and take away given hash
perform uniformly distribute parts within the bucket.
2. Ordering
HashSet doesn’t
keep any order whereas LinkedHashSet maintains insertion order of parts very similar to Checklist interface and TreeSet maintains
sorting order or parts.
3. Inside
Implementation
HashSet is backed by a HashMap
occasion, LinkedHashSet is carried out utilizing HashSet and
LinkedList whereas TreeSet is backed up by NavigableMap in Java
and by default it makes use of TreeMap.
4. null
Each HashSet and LinkedHashSet permits
null however TreeSet would not enable null however TreeSet would not enable
null and throw java.lang.NullPointerException
when you’ll insert null into TreeSet. Since TreeSet makes use of compareTo() methodology of
respective parts to match them
which throws NullPointerException whereas evaluating with null,
right here is an instance:
TreeSet cities
Exception in thread “principal” 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)
HashSet and LinkedHashSet makes use of equals() methodology in Java for comparability however TreeSet makes use of compareTo() methodology for
sustaining ordering. That is why compareTo() should be
constant to equals in Java. failing to take action break normal contact of Set
interface i.e. it may well allow duplicates.
And, for those who wish to see the distinction in tabular format, here’s a good desk which highlights the important thing distinction between TreeSet, LinkedHashSet, and HashSet in Java
TreeSet vs HashSet vs LinkedHashSet – Instance

program. On this instance we’re demonstrating distinction in ordering, time
taking whereas inserting 1M data amongst TreeSet, HashSet and LinkedHashSet in Java.
This may assist to solidify some factors which mentioned in earlier part and
assist to determine when to make use of HashSet, LinkedHashSet or TreeSet in Java.
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.TreeSet;/**
* Java program to exhibit distinction between TreeSet, HashSet and LinkedHashSet
* in Java Assortment.
* @writer
*/
public class SetComparision
{
public static void principal(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 in HashSet – parts saved in random order
System.out.println(“Ordering in HashSet :” + fruitsStore);
//insertion
order or parts – LinkedHashSet storeds parts as insertion
System.err.println(“Order of aspect in LinkedHashSet
:” + fruitMarket);
//must be sorted order – TreeSet shops aspect in sorted
order
System.out.println(“Order of objects in TreeSet
:” + fruitBuzz);
//Efficiency check to insert 10M parts in HashSet, LinkedHashSet
and TreeSet
Set<Integer> numbers = new HashSet<Integer>();
lengthy startTime = System.nanoTime();
for(int i =0; i<10000000; i++){
numbers.add(i);
}
lengthy endTime = System.nanoTime();
System.out.println(“Whole time to insert 10M
parts in HashSet in sec : “
+ (endTime – startTime));
// LinkedHashSet efficiency
Take a look at – 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(“Whole time to insert 10M
parts in LinkedHashSet in sec : “
+ (endTime –
startTime));
// TreeSet efficiency Take a look at – 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(“Whole time to insert 10M
parts in TreeSet in sec : “
startTime));
}
}
Output
Ordering in HashSet :
Order of aspect in LinkedHashSet :[mango, apple, banana]
Order
of objects in TreeSet :[apple, banana, mango]
Whole time to insert 10M parts in HashSet in sec : 3564570637
Whole time to insert 10M parts in LinkedHashSet in sec : 3511277551
Whole time to insert 10M parts in TreeSet in sec : 10968043705
When to make use of HashSet, TreeSet and LinkedHashSet in Java
frequent Set operations like not permitting duplicates however since HashSet, TreeSet and LinkedHashSet has there
particular characteristic which makes them applicable in sure state of affairs.
Due to sorting
order offered by TreeSet, use TreeSet whenever you
want a set the place parts are sorted with out duplicates. HashSet are rather normal goal
Set implementation, Use it as default Set
implementation for those who want a quick, duplicate free assortment.
Whereas LinkedHashSet is
extension of HashSet and its extra appropriate the place you
want to keep up insertion order of parts, similar to Checklist without compromising
efficiency for expensive TreeSet.
One other use of LinkedHashSet is for
creating copies of current Set, Since LinkedHashSet preservers
insertion order, it returns Set which accommodates identical parts in identical order like
actual copy.
In brief, though all three
are Set interface implementation they provide distinctive characteristic, HashSet is a
normal goal Set whereas LinkedHashSet offers insertion order
assure and TreeSet is a SortedSet which shops
parts in sorted order specified by Comparator or Comparable in Java.
How you can
copy object from one Set to different
exhibit How LinkedHashSet can be utilized to repeat objects from one
Set to a different with out shedding order. You’re going to get actual duplicate of supply Set, in phrases
of contents and order. Right here static methodology copy(Set supply) is written
utilizing Generics, This type of parameterized methodology provides type-safety and assist
to keep away from ClassCastException at runtime.
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;
/**
* Java program to copy object from one HashSet to a different utilizing LinkedHashSet.
* LinkedHashSet preserves order of aspect whereas copying parts.
*
* @writer Javin
*/
public class
SetUtils{
public static void
principal(String args[]) {
HashSet<String> supply = new
HashSet<String>(Arrays.asList(“Set, Checklist, Map”));
System.out.println(“supply : “ + supply);
Set<String> copy = SetUtils.copy(supply);
System.out.println(“copy of HashSet utilizing LinkedHashSet: “ +
copy);
}
/*
* Static utility methodology to repeat Set in Java
*/
public static <T> Set<T> copy(Set<T>
supply){
return
new LinkedHashSet<T>(supply);
}
}
Output:
supply : [Set, List, Map]
copy of HashSet utilizing LinkedHashSet: [Set,
List, Map]
At all times code for interface than implementation with the intention to change HashSet to LinkedHashSet or TreeSet when your
requirement adjustments. That’s all on the distinction
between HashSet, LinkedHashSet, and TreeSet in Java. If you recognize
some other vital distinction between TreeSet, LinkedHashSet, and HashSet which is
value remembering then please add as a remark.
Different tutorials from Java Assortment Framework