dsa

Java LinkedHashSet

In this tutorial, we will learn about the Java LinkedHashSet class and its methods with the help of examples.

The LinkedHashSet class of the Java collections framework provides functionalities of both the hashtable and the linked list data structure.

LinkedHashSet class which is implemented in the collections framework is an ordered version of HashSet that maintains a doubly-linked List across all elements. When the iteration order is needed to be maintained this class is used. When iterating through a HashSet the order is unpredictable, while a LinkedHashSet lets us iterate through the elements in the order in which they were inserted. Let’s see how to create a set object using this class.

linkedhashset

Example:

// Java Program to illustrate the LinkedHashset Class 
import java.util.*;
public class HashSetDemo {

   public static void main(String args[]) {
      // create a hash set
      LinkedHashSet hs = new LinkedHashSet();
      
      // add elements to the hash set
      hs.add("B");
      hs.add("A");
      hs.add("D");
      hs.add("E");
      hs.add("C");
      hs.add("F");
      System.out.println(hs);
   }
}
output:
[B, A, D, E, C, F]

the list of constructors supported by the LinkedHashSet

Sr.No. Constructor & Description
1

HashSet( )

This constructor constructs a default HashSet.

2

HashSet(Collection c)

This constructor initializes the hash set by using the elements of the collection c.

3

LinkedHashSet(int capacity)

This constructor initializes the capacity of the linkedhashset to the given integer value capacity. The capacity grows automatically as elements are added to the HashSet.

4

LinkedHashSet(int capacity, float fillRatio)

This constructor initializes both the capacity and the fill ratio (also called load capacity) of the hash set from its arguments.

Given below are the list of constructors supported by the LinkedHashSet

  • LinkedHashSet(): This constructor is used to create a default HashSet.
  • LinkedHashSet(Collection C): Used in initializing the HashSet with the eleements of the collection C
  • LinkedHashSet(int size): Used to initialize the size of the LinkedHashSet with the integer mentioned in the parameter.
  • LinkedHashSet(int capacity, float fillRatio): Can be used to initialize both the capacity and the fill ratio, also called the load capacity of the LinkedHashSet with the arguments mentioned in the parameter. When the number of elements exceeds the capacity of the hash set is multiplied with the fill ratio thus expanding the capacity of the LinkedHashSet