×

Differences and Similarities between HashSet, LinkedHashSet and TreeSet in Java

HashSet Class:

The HashSet is a class that executes the Setpoint of interaction. It is utilised to store the items in a hashtable; a hashtable is an information structure which holds information in an ArrayList. It gives speedy admittance to the data utilising the cluster record. Using a HashSet, we can embed, update, and eliminate the components effectively.

Some features of the HashSet class:

  • HashSet uses a system called "Hashing" to store the components.
  • Iutiliseses a hashtable information design to keep the pieces.
  • It contains remarkable details.
  • It permits putting away invalid qualities.
  • It is a non-synchronized class.
  • It doesn't give an instrument to keep up with the inclusion request. So the components will be embedded in light of the Hashcode.
  • It is a helpful instrument for hunting activities.
  • By default, it involves 16 as the underlying size of the hashtable.
  • It broadens AbstractSet class and executes the Setpoint of interaction.
  • It likewise executes the Cloneable and Serializable connection points.

Declaration of the HashSet class:

A HashSet class can be declared as follows:

public class HashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable, Serializable 

Example:

//simple program to understand the HashSet using String data
import java.util.HashSet;     //importing the HashSet class from the util package
import java.util.Iterator;      //importing the Iterator class from the util package
public class HSD         //creating the public class with the name HSD
{  
     public static void main(String args[]){    
        HashSet<String> h=new HashSet();   //here, we are implementing the HashSet  
               h.add("John");    //here, we are adding the elements to the HashSet 
               h.add("Jack");     //we use add method to add the elements to the HashSet
               h.add("Anil");     
               h.add("Sai");    
               h.add("Shiva");  
               Iterator<String> i=h.iterator();  //here we are using the iterator method to                 //print the elements of HashSet 
               while(i.hasNext())  //here, we return true if the Scanner has another token //input  
               {    
               System.out.println(i.next());      //here, we are printing the elements of the //HastSet   
               }    
     }    
}

Output:

John
Jack
Anil
Sai
Shiva

Example 1:

//simple program to understand the HashSet using the Integer data
import java.util.HashSet;     //importing the HashSet class from the util package
import java.util.Iterator;      //importing the Iterator class from the util package
public class HSD         //creating the public class with the name HSD
{  
     public static void main(String args[]){    
        HashSet<String> h=new HashSet();   //here, we are implementing the HashSet  
               h.add(100);    //here, we are adding the elements to the HashSet 
               h.add(200);     //we use add method to add the elements to the HashSet
               h.add(300);     
               h.add(400);    
               h.add(500);  
               Iterator<String> i=h.iterator();  //here we are using the iterator method to                 //print the elements of HashSet 
               while(i.hasNext())  //here, we return true if the Scanner has another token //input  
               {    
               System.out.println(i.next());      //here, we are printing the elements of the //HastSet   
               }    
     }    
}

Output:

100
200
300
400
500

LinkedHashSet class:

 LinkedHashSet class is like the HashSet class; it is an arranged form of HashSet. In addition, it permits us to keep up with the inclusion request of the components. It acquires the HashSet class and executes the Setpoint of interaction. It likewise utilises a hashtable to store the details. It permits us to effortlessly embed, update, eliminate, and keep up with the components.

The following are a few elements of the LinkedHashSet:

  • It contains exceptional components.
  • It utilises a hashtable and a doubly-connected rundown to store and keep up with the components.
  • It can have invalid components.
  • It gives a choice set activity.
  • It is non-synchronized.
  • It permits a simple method for keeping up with the additional order. erted given the Hashcode.
  • It is a valuable component of the hunting activity.
  • Bu default involves 16 as the underlying size of the hashtable.
  • It broadens AbstractSet class and carries out the Set connection point.
  • It additionally executes the Cloneable and Serializable connection points.

Declaration of the LinkedHashSet class:

A LinkedHashSet class can be declared as follows:

public class LinkedHashSet<E> extends HashSet<E> implements Set<E>, Cloneable, Serializable 

Example:

//simple program for the understanding of LinkedHashSet class
import java.util.LinkedHashSet;     //importing the HashSet class from the util //package
import java.util.Iterator;      //importing the Iterator class from the util package
public class HSD         //creating the public class with the name HSD
{  
     public static void main(String args[]){    
        LinkedHashSet<String> ln=new LinkedHashSet();   //here, we are implementing //the LinkedHashSet  
               ln.add("John");    //here, we are adding the elements to the LinkedHashSet 
  ln.add("Jack");     //we use add method to add the elements to the HashSet
               ln.add("Anil");     
               ln.add("Sai");    
               ln.add("Shiva");  
    System.out.println(“Printing the elements of the LinkedHashSet using the iterator method:”);                
Iterator<String> i=h.iterator();  //here we are using the iterator method to                 //print the elements of HashSet 
               while(i.hasNext())  //here, we return true if the Scanner has another token //input  
               {    
               System.out.println(i.next());      //here, we are printing the elements of the //HastSet   
               }    
     }    
}

Output:

Printing the elements of the LinkedHashSet using the iterator method:
John
Jack
Anil
Sai
Shiva

Example 1:

//simple program to understand the LinkedHashSet using the Integer data
import java.util.LinkedHashSet;     //importing the HashSet class from the util //package
import java.util.Iterator;      //importing the Iterator class from the util package
public class HSD         //creating the public class with the name HSD
{  
     public static void main(String args[]){    
        LinkedHashSet<String> ln=new LinkedHashSet();   //here, we are implementing //the LinkedHashSet  
               ln.add(100);    //here, we are adding the elements to the LinkedHashSet 
               ln.add(200);     //we use add method to add the elements to the //LinkedHashSet
               ln.add(300);     
               ln.add(400);    
               ln.add(500);  
   System.out.println(“Printing the elements of the LinkedHashSet using the iterator method:”);               
Iterator<String> i=h.iterator();  //here we are using the iterator method to                 //print the elements of linkedHashSet 
               while(i.hasNext())  //here, we return true if the Scanner has another token //input  
               {    
               System.out.println(i.next());      //here, we are printing the elements of the //linkedHastSet   
               }    
     }    
}

Output:

Printing the elements of the LinkedHashSet using the iterator method:
100
200
300
400
500

TreeSet class:

Java TreeSet class carries out the Set connection point that involves a tree for capacity. It acquires AbstractSet class and executes the NavigableSet interface. The objects of the TreeSet class are put away in the rising requests.

The significant focuses of the Java TreeSet class are:

  • Java TreeSet class contains one-of-a-kind components just like HashSet.
  • Java TreeSet class access and recovery times hush up quick.
  • Java TreeSet class doesn't permit invalid components.
  • Java TreeSet class is non-synchronised.
  • Java TreeSet class keeps rising control.
  • Java TreeSet class contains particular components just like HashSet.
  • Java TreeSet class access and recovery times are rapid.
  • Java TreeSet class doesn't permit invalid components.
  • Java TreeSet class is non-synchronized.
  • Java TreeSet class keeps climbing control.
  • The TreeSet can permit those nonexclusive kinds that are similar. For instance, the StringBuffer class carries out the Tantamount connection point.

Working of The TreeSet Class:

TreeSet is being carried out utilising a paired inquiry tree, which is self-adjusting very much like a Red-Dark Tree. Like this, tasks like hunt, eliminate, and add consume O(log(N)) time. The purpose of this is there in oneself adjusting the tree. It guarantees that the tree level never surpasses O(log(N)) for the entirety of the referenced tasks. Like this, it is one of the proficient information structures to keep the enormous information arranged and do procedures.

Synchronisation of The TreeSet Class:

As currently referenced over, the TreeSet class isn't synchronised. If more than one string simultaneously gets to a tree set, and one of the getting to strings changes it, then the synchronisation should be done physically. It is usually finished by doing some object synchronisation that epitomises the set. Be that as it may, for the situation where no such article is found, the group should be wrapped with the assistance of the Collections. synchronised set() technique. It is encouraged to utilise the method during creation time to avoid the set’s unsynchronised access. The accompanying code scrap shows something similar.

TreeSet Class Declaration:

A TreeSet class can be declared as follows:

public class TreeSet<E> extends AbstractSet<E> implements NavigableSet<E>, Cloneable, Serializable   

Example:

//simple program to understand the TreeSet using String data
import java.util.*;     //importing the TreeSet class from the util package
import java.util.Iterator;      //importing the Iterator class from the util package
public class HSD         //creating the public class with the name HSD
{  
     public static void main(String args[]){    
        TreeSet< String > h=new TreeSet< String >();   //here, we are implementing the // TreeSet  
               h.add("John");    //here, we are adding the elements to the TreeSet 
               h.add("Jack");     //we use add method to add the elements to the TreeSet
               h.add("Anil");     
               h.add("Sai");    
               h.add("Shiva");  
  System.out.println(“Printing the elements of the TreeSet using the iterator method:”);               
Iterator<String> i=h.iterator();  //here we are using the iterator method to                 //print the elements of HashSet 
               while(i.hasNext())  //here, we return true if the Scanner has another token //input  
               {    
               System.out.println(i.next());      //here, we are printing the elements of the //HastSet   
               }    
     }    
}

Output:

Printing the elements of the TreeSet using the iterator method:
John
Jack
Anil
Sai
Shiva

Example 1:

//simple program to understand the TreeSet using the Integer data
import java.util.*;     //importing the TreeSet class from the util package
import java.util.Iterator;      //importing the Iterator class from the util package
public class HSD         //creating the public class with the name HSD
{  
     public static void main(String args[]){    
        TreeSet< String > h=new TreeSet< String >();   //here, we are implementing the // TreeSet  
               h.add(120);    //here, we are adding the elements to the TreeSet 
               h.add(200);     //we use add method to add the elements to the TreeSet
               h.add(300);     
               h.add(400);    
               h.add(450);  
   System.out.println(“Printing the elements of the TreeSet using the iterator method:”);
               Iterator<String> i=h.iterator();  //here we are using the iterator method to                 //print the elements of HashSet 
               while(i.hasNext())  //here, we return true if the Scanner has another token //input  
               {    
               System.out.println(i.next());      //here, we are printing the elements of the //HastSet   
               }    
     }    
}

Output:

//simple program to understand the TreeSet using the Integer data
import java.util.*;     //importing the TreeSet class from the util package
import java.util.Iterator;      //importing the Iterator class from the util package
public class HSD         //creating the public class with the name HSD
{  
     public static void main(String args[]){    
        TreeSet< String > h=new TreeSet< String >();   //here, we are implementing the // TreeSet  
               h.add(120);    //here, we are adding the elements to the TreeSet 
               h.add(200);     //we use add method to add the elements to the TreeSet
               h.add(300);     
               h.add(400);    
               h.add(450);  
   System.out.println(“Printing the elements of the TreeSet using the iterator method:”);
               Iterator<String> i=h.iterator();  //here we are using the iterator method to                 //print the elements of HashSet 
               while(i.hasNext())  //here, we return true if the Scanner has another token //input  
               {    
               System.out.println(i.next());      //here, we are printing the elements of the //HastSet   
               }    
     }    
}

Similarities between HashSet, LinkedHashSet and TreeSet:

1) Copies: Each of the three carries out a Set interface implies they are not permitted to store copies.

2) String wellbeing: HashSet, TreeSet, and LinkedHashSet are not strung safely; assuming you use them in a multi-stringing climate where something like String alters Set, you want to synchronise them remotely.

3) Fall flat Quick Iterator: Iterator returned by TreeSet, LinkedHashSet, and HashSet come up short quick Iterator. for example, Assuming Iterator is altered after its creation by the way other than Iterators eliminate() technique, it will toss ConcurrentModificationException with best of exertion.

Differences between HashSet, LinkedHashSet and TreeSet:

Internal Working of Sets:

  • HashSet inside involves HashMap for putting away articles
  • LinkedHashSet utilises LinkedHashMap inside to store objects
  • TreeSet utilises TreeMap inside to store objects

At the point when To Utilize or use the Sets:

  • To keep up with inclusion requests, however, we need to store novel articles
  • To keep up with the inclusion request of components then, you can utilise LinkedHashSet
  • To sort the components as indicated by some Comparator then, at that point, use TreeSet

Order of the Sets:

  • HashSet doesn't keep up with an additional request
  • LinkedHashSet keeps up with the additional request for items
  • While TreeSet orders the components as indicated by provided Comparator. Of course, articles will be put by their standard rising request.

The complexity of Operations Performed on the Sets:

  • HashSet gives O(1) intricacy for inclusion, eliminating, and recovering articles
  • LinkedHashSet gives addition, eliminating, and recovering tasks execution altogether O(1).
  • While TreeSet provides the presentation of request O(log(n)) for addition, eliminating, and recovering tasks.

Performance of the Sets:

  • The presentation of HashSet is better when contrasted with LinkedHashSet and TreeSet.
  • The exhibition of LinkedHashSet is more slow than TreeSet. It is practically like HashSet, however more slow in light of the fact that LinkedHashSet inside keeps up with LinkedList to keep up with the additional request of components
  • TreeSet execution is superior to LinkedHashSet, aside from inclusion and evacuation activities, since it needs to sort the components after every addition and expulsion activity.

Memory Occupation of Sets:

  • HashSet requires less memory than LinkedHashSet and TreeSet as it utilises just HashMap inside to store its components.
  •  LinkedHashSet requires more memory than HashSet as it likewise keeps up with LinkedList along with HashMap to store its components.
  • TreeSet likewise requires more memory than HashSet as it additionally keeps up with Comparator to sort the components alongside the TreeMap.

Compare the Sets:

  • HashSet utilises equals() and hashCode() techniques to think about the items
  • LinkedHashSet utilizes equals to() and hashCode() techniques to analyze it's articles
  • TreeSet utilizes think about() and compareTo() strategies to look at the articles

Null Components or elements of the sets:

  • HashSet permits just a single invalid worth.
  • LinkedHashSet permits just a single invalid worth.
  • TreeSet doesn't allow invalid worth. Assuming you embed invalid worth into TreeSet, it will toss NullPointerException.

Iterator of the Sets:

Iterator returned by every one of the three Set executions is come up short quick, and that implies assuming you change assortment once emphasis starts. For example , adding or erasing components without utilising Iterator's eliminate strategy will toss ConcurrentModificationException.

Likewise, the Iterator of HashSet ensures no structure, while the Iterator of LinkedHashSet allows you to emphasise that the request components are added.


Related Topics

Difference Between replace() and replaceall() in Java

In this article, you will be acknowledged about the replace() and replaceall() methods in java. Also, most importantly you will be acknowledged the differences between them along with the example...

4 minutes read.

Java LinkedList

LinkedList Java The Java LinkedList is used to store the elements by using a doubly linked list. It contains the duplicate items, also maintains the order of the insertion, the class...

5 minutes read.

Java Program to Create Set of Pairs Using HashSet

HashSet in Java: HashSet is an assortment in Java that has a place with java.util bundle. It inside utilises HashMap to store components. It is an execution of the Set connection...

11 minutes read.

Grepcode Java util date

What is java.util.Date Class? The date and time in Java are provided through the java.util.Date class. If you imported java.util, it could be helpful. Use the Java.util.Date class to implement this class...

4 minutes read.

Crown Pattern in Java

We know the importance of solving pattern problems. We can solve pattern problems by using any programming language. There is no rule to translating into a particular programming language. We...

4 minutes read.

Skyline Problem in Java

The skyline of a city is the outer edge of the pattern created by all of its structures when viewed from a distance. Return the skyline that these buildings together...

4 minutes read.

Java Pass-by-Reference

In Java, passing parameters can be done using one of two fundamental methods. Pass-by-value is used for the first and pass-by-reference is used for the second. One thing to keep...

2 minutes read.

Java Integer toHexString() method

The toHexString() method of Java Integer class returns a string representing the specified int argument as an unsigned integer in base 16. Syntax public static String toHexString (int  i)  Parameters The parameter ‘i’ represents...

1 minute read.

Switch Case with Enum in Java

From some conditions, the java switch statement executes one statement. Similar to the If-Else-If ladder statement, this can be Byte, short, int, long, enum, string, and some wrapper types like...

4 minutes read.

Economical number in Java

Economical number is said to be economically efficient if the number of digits after prime factorization of the original number with their powers is less than the number of digits...

3 minutes read.

How to Convert long to int in Java

How to Convert long to int in Java When we assign a larger type value to a variable of smaller type, then we need to perform explicit casting for the conversion....

2 minutes read.

Java Math tanh() Method

The tanh() method of Java Math class returns the hyperbolic tangent of the specified double value. Syntax: public static double tanh(double x) Parameters: The parameter ‘x’ represents the number whose hyperbolic tangent is to...

2 minutes read.

Application of Array in Java

In this article we are going to acknowledge about what the array is, types of arrays and their applications. What is an array? An array is often a set of interrelated elements...

4 minutes read.

Java Code Coverage Tools

Code coverage testing is a crucial metric that gauges how thoroughly the program's source code has been tested. The market is flooded with Code Coverage Tools, making it difficult to...

7 minutes read.

Java Boyer Moore

A string searching or matching technique called the Boyer-Moore algorithm was created in 1977 by Robert S. Boyer and J. Strother Moore. It is the most popular and effective string-matching...

9 minutes read.

Maximum length of string in java

In java, String can act as a data type and a class. The string can be defined as the collection of characters that are enclosed with double quotes(“ “). The...

3 minutes read.

Lombok Java

What is Lombok java? A well-liked and widely-used Java framework that is used to reduce or eliminate boilerplate code is called Project Lombok. Both time and effort are saved. We may...

7 minutes read.

Java List Implementations

ArrayList and LinkedList are the two implementations of List that are for general-purpose. You'll probably utilise an array list the majority of the time because it's quick and provides constant-time...

3 minutes read.

How to Convert String to Integer in Java

How to convert String to int in Java You need to convert String into int if you want to perform a mathematical operation on string which contains digits. To do so,...

3 minutes read.

Pernicious Number in Java

If the number of 1s in a number appearing in the binary representation is the prime number, such a number is known as a pernicious number. A pernicious number always corresponds to...

4 minutes read.