Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is LinkedHashSet?
3.
Constructors for LinkedHashSet
4.
Methods of LinkedHashSet
5.
Frequently Asked Questions
6.
Conclusion
Last Updated: Mar 27, 2024
Easy

LinkedHashSet

Introduction

The Set interface in the Collection Framework is a child of Collection. It's often helpful to use LinkedHashSets to keep the order of a collection of objects when duplicates aren't allowed, and the insertion order isn't preserved. This article is about LinkedHashSet in detail.

Also Read About, Multithreading in java

What is LinkedHashSet?

HashSet is a child class of LinkedHashSet. It combines two data structures: Hash Table and Linked List, which is a hybrid Data Structure

In LinkedHashSet, all elements remain doubly linked across all elements in an ordered version of HashSet. In cases where you care about the iteration order, this class is better than HashSet. 

LinkedHashSet allows you to iterate through elements in the order they were inserted, while HashSet lets you iterate through elements in an unpredictable order. 

For insertion, removal, and retrieval, the LinkedHashSet exhibits the performance of order O(1). It has an initial default capacity of 16 and a load factor of 0.75.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Constructors for LinkedHashSet

There are four constructors for LinkedHashSet:
 

  1. LinkedHashSet lh=new LinkedHashSet(); // A LinkedHashSet object is created with an initial capacity of 16 and a Fill ratio of 0.75 (also known as Load Factor).
     
  2. LinkedHashSet lh=new LinkedHashSet(int initialCapacity); // A LinkedHashSet with customized capacity is created.
     
  3. LinkedHashSet h=new LinkedHashSet(int initialCapacity, float load factor); //A LinkedHashSet is created with a customized initial capacity and load factor.
     
  4. LinkedHashSet h=new LinkedHashSet(Collection c); // A LinkedHashSet object is created from the given collection. This allows conversion between Collection objects.
     

Here is a java program for creating a LinkedHashSet by using another collection.

import java.util.*;
public class Main {
    public static void main(String args[]) {        
      LinkedHashSet lh=new LinkedHashSet<>();  
      lh.add("kashish");  
      lh.add("2022");  
      lh.add("4");
      lh.add(null);
      lh.add("three");
      System.out.println(lh);
    }
}

 


Output:

Methods of LinkedHashSet

Method

Description

add(e) An element is added if it isn't already in the Set.
clear() Everything in the Set is removed.
clone() This function returns a copy of the LinkedHashSet instance, which does not clone the elements.
equals() The function returns true if the specified object matches this set.
contains(Object) This set includes the element specified by the element.
isEmpty() If the Set does not contain elements, it is returned as true.
iterator() If the Set contains elements, it is returned as true.
remove(Object) This set is removed if it contains any elements.
size() It returns the size of the set.
spliterator() This function splits the elements late-binding and fail-fast.
toString() This function returns this collection as a string.
toArray() This function returns an array of all the elements in this Collection.

Below is the implementation for some methods:

import java.io.*;
import java.util.*;
public class Main {
    public static void main(String[] args) {
        //creating an object for LinkedHashSet
        Set < String > lh = new LinkedHashSet < String > ();

        // Adding elements the  using add()
        lh.add("Kashish");
        lh.add("Saxena");
        lh.add("21");
        lh.add("Coding");
        lh.add("Ninjas's");

        // removing elements from the LinkedHashSet
        lh.remove("21");
        System.out.println("After removing the element: " + lh);

        // Check if the LinkedHashSet contains an element?
        System.out.println("Checking if the element is present? " + lh.contains("Coding"));

        // Iterating the elements using iterators
        Iterator i = lh.iterator();
        while (i.hasNext())
            System.out.print(i.next() + "_");
        System.out.println();
    }
}

 

Output:

Try it by yourself on java online compiler.

Frequently Asked Questions

  1. What are the disadvantages of using the LinkedHashSet?
    Element iteration is slower than with ArrayLists.
    Access to random elements is inefficient.
    There is an additional memory overhead involved with keeping track of the next element in the list.
     
  2. What have linked hash sets and linked hash maps?
    The elements in LinkedHashMap are in key-value pairs, so they have only one null key and multiple null values. A LinkedHashSet is simply a collection of things with a single null value.
     
  3. How do LinkedHashSets and TreeSets differ?
    The linked hash set maintains the insertion order of elements. Elements are inserted in the order they are added. Based on a Comparator supplied by TreeSet, the elements are ordered. In the absence of a comparator, elements will be sorted in their natural ascending order.
     
  4. Difference between the HashSet and LinkedHashSet.
HashSet LinkedHashSet
The underlying data structure is Hashtable. The underlying data structure is Hash Table and Linked List.
Insertion order is not preserved. Insertion order is preserved.
HashSet is introduced in the 1.2 version. LinkedHashSet is introduced in the 1.4 version.

Also read about - hash function in data structure

Conclusion

In this blog, we have seen what LinkedHashSet is in the Collection Framework and the methods and features of LinkedHashSet.

We hope that this blog has helped you enhance your knowledge about LinkedHashSet and if you would like to learn more, check out our articles on the link. Do upvote our blog to help other ninjas grow. Happy Coding!

Previous article
SortedSet
Next article
NavigableSet
Live masterclass