×

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

JDBC vs ODBC

Difference Between JDBC and ODBC ODBC: ODBC (Open Database Connectivity) is the accepted method for accessing databases among organisations and programmers. A database is linked to other programmes, such as word processors, spreadsheets,...

4 minutes read.

How to Convert String to enum in Java?

In this article, we shall gain the complete knowledge about how to convert the string to enum in Java. The complete process that happens in the approach shall be discussed...

3 minutes read.

Java Single Linkedlist

Like arrays, linked lists are a type of linear data structure. Unlike arrays, which store each element in the same location, linked lists employ pointers to connect the elements together. In...

25 minutes read.

Shift right zero Fill Operator in Java and Operator Shifting

Left shift operator ( << ) : The left shift operator is an operator which performs its action at the bits level of a binary Operator. That means when you perform...

4 minutes read.

Even Odd Program in Java

Even Odd Program in Java The number that are completely divisible by 2 are even and the number that leaves remainder are odd numbers. For example, the numbers 2, 0, 4,...

5 minutes read.

Figurate Number in Java

There have been several uses for figurate or figural numerals throughout history. A number that may be expressed by regular, distinct geometric shapes with spaced evenly points is referred to...

4 minutes read.

How to Convert Hexadecimal to Decimal in Java

How to Convert Hexadecimal to Decimal in Java There are two methods to convert Hexadecimal to Decimal: Using parseInt() method Using user-defined logic Using Integer.parseInt() method It is a static method of...

2 minutes read.

Longest Odd Even Subsequence in Java

In order to solve the Java problem known as the longest odd-even subsequence, one must identify a sequences in a non-negative array having size s that alternately includes odd and...

6 minutes read.

Java String lastIndexOf() method

Java String lastIndexOf() method returns last index of character or substring in a String. Syntax: Method Description int lastIndexOf(int ch)It returns last index position for the given char valueint lastIndexOf(int ch, int...

2 minutes read.

StringBuilder in Java

StringBuilder in Java Java StringBuilder class is introduced since JDK 1.5. The StringBuilder class is mainly used to create modifiable or mutable strings. Note that the StringBuilder class is not synchronized....

7 minutes read.

Java Math acos() Method

The acos() method of Math class computes the trigonometric Arc Cosine (inverse of cosine ) of an angle. The value returned is between 0.0 to pi. Syntax: public static double acos(double a) Parameters: The...

1 minute read.

How to Convert int to double in Java

How to Convert int to double in Java When two variables of different types are involved in the single expression, Java compiler uses built-in library function to convert the variable to...

2 minutes read.

Java Substring

What is a substring in Java? Here by the name  " substring " itself, we can easily come to know it is a part of a string or a subset of...

4 minutes read.

Java Command Line Arguments

Java command line arguments Command line argument is an input or argument to the program when you run the program. In Java, we can take the inputs from the console, and...

2 minutes read.

Switch Case Program in Java

Switch Case Program in Java The switch case program in Java controls which code snippet gets executed on the basis of the value of the expression mentioned in the switch statement....

22 minutes read.

Undo and Redo Operations in Java

Undo and redo operation are the most widely used operation while dealing with file. In this section, we will discuss how to implement undo and redo operation in Java. Undo Redo...

2 minutes read.

Bin Packing Problem Java

Assigning some items with known weights to bins with consistent capacities is necessary for the bin packing problem. The goal is to use the smallest possible boxes while ensuring everything is put...

6 minutes read.

Object class in Java

In Java, a class is a file containing the Java byte code. It can essentially specifically be executed on the JVM (Java Virtual Machine), fairly significant. The JVM mostly generally...

6 minutes read.

Zebra Puzzle Problem in Java

Complex puzzles like the zebra puzzle demand a lot of work and mental training to complete. Because it was created by renowned German scientist Albert Einstein, it is also sometimes...

10 minutes read.

How to convert String to String array in Java

A String in Java is a thing that indicates a collection of letters. We must include the String class from java.lang package if we want to be using strings. An...

5 minutes read.