Java LinkedHashSet Class

In Java, LinkedHashSet is a class that extends the HashSet class and implements the Set interface. It maintains a doubly-linked list of the elements in the set, which defines the iteration order. Like HashSet, LinkedHashSet also allows for O(1) average case performance for basic operations, such as adding, removing, and checking for the presence of elements in the set.

However, unlike HashSet, LinkedHashSet maintains the order of insertion of elements. That is, when you iterate through the elements in a LinkedHashSet, they will be returned in the order in which they were added to the set.

The LinkedHashSet class also provides several constructors, which allow you to specify the initial capacity and load factor of the set, as well as whether it should be ordered by insertion order or by access order (which means the order in which the elements were last accessed).

Here’s an example of how to create and use a LinkedHashSet:

import java.util.LinkedHashSet;

public class Main {
    public static void main(String[] args) {
        LinkedHashSet<String> set = new LinkedHashSet<>();

        // Adding elements to the set
        set.add("apple");
        set.add("banana");
        set.add("orange");
        set.add("pear");

        // Printing the set in insertion order
        System.out.println(set);

        // Removing an element from the set
        set.remove("banana");

        // Checking if an element is in the set
        System.out.println(set.contains("pear"));

        // Iterating through the set
        for (String fruit : set) {
            System.out.println(fruit);
        }
    }
}

This will output:

[apple, banana, orange, pear]
true
apple
orange
pear

Hierarchy of LinkedHashSet class:

The LinkedHashSet class in Java is part of the Java Collections Framework and is a subclass of the HashSet class. It implements the Set interface and adds the feature of maintaining the order of insertion of elements using a doubly-linked list.

The class hierarchy of LinkedHashSet can be represented as follows:

java.lang.Object
    java.util.AbstractCollection<E>
        java.util.AbstractSet<E>
            java.util.HashSet<E>
                java.util.LinkedHashSet<E>

As you can see, LinkedHashSet inherits from HashSet, which in turn inherits from AbstractSet. AbstractSet is a subclass of AbstractCollection, which is a base class for all collections in the Java Collections Framework.

LinkedHashSet also implements the Set interface, which extends the Collection interface. The Set interface provides a collection of unique elements and does not allow duplicates. The LinkedHashSet class uses a hash table to store the elements and also maintains a doubly-linked list to preserve the order of insertion.

So, in summary, LinkedHashSet is a specialized implementation of HashSet that maintains the order of insertion of elements using a doubly-linked list.

LinkedHashSet Class Declaration:

The declaration of the LinkedHashSet class in Java is as follows:

public class LinkedHashSet<E> extends HashSet<E> implements Set<E>, Cloneable, Serializable {
    // Constructors
    public LinkedHashSet();
    public LinkedHashSet(int initialCapacity);
    public LinkedHashSet(int initialCapacity, float loadFactor);
    public LinkedHashSet(Collection<? extends E> c);

    // Methods specific to LinkedHashSet
    public boolean add(E e);
    public void clear();
    public Object clone();
    public boolean contains(Object o);
    public boolean isEmpty();
    public Iterator<E> iterator();
    public boolean remove(Object o);
    public int size();
}

As mentioned earlier, LinkedHashSet extends the HashSet class and implements the Set interface. It also provides several constructors, including the default constructor, a constructor that allows you to specify an initial capacity, a constructor that allows you to specify both an initial capacity and a load factor, and a constructor that takes a collection and adds all its elements to the LinkedHashSet.

In addition to the methods inherited from HashSet and Set, LinkedHashSet provides several methods specific to it. These include methods to add an element, clear the set, check if an element is present, return an iterator to traverse the set, remove an element, and get the size of the set.

LinkedHashSet also implements the Cloneable and Serializable interfaces, which allow you to create copies of the set and serialize/deserialize it, respectively.

Constructors of Java LinkedHashSet Class:

The LinkedHashSet class in Java provides four constructors that allow you to create a new LinkedHashSet object:

  1. public LinkedHashSet(): Creates an empty LinkedHashSet with the default initial capacity (16) and load factor (0.75).
  2. public LinkedHashSet(int initialCapacity): Creates an empty LinkedHashSet with the specified initial capacity and the default load factor (0.75).
  3. public LinkedHashSet(int initialCapacity, float loadFactor): Creates an empty LinkedHashSet with the specified initial capacity and load factor.
  4. public LinkedHashSet(Collection<? extends E> c): Creates a LinkedHashSet containing all the elements in the specified collection.

Here is an example that demonstrates how to use each constructor:

import java.util.LinkedHashSet;
import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        // Constructor 1: Create an empty LinkedHashSet
        LinkedHashSet<String> set1 = new LinkedHashSet<>();

        // Constructor 2: Create an empty LinkedHashSet with initial capacity
        LinkedHashSet<String> set2 = new LinkedHashSet<>(10);

        // Constructor 3: Create an empty LinkedHashSet with initial capacity and load factor
        LinkedHashSet<String> set3 = new LinkedHashSet<>(10, 0.5f);

        // Constructor 4: Create a LinkedHashSet from a collection
        String[] fruits = {"apple", "banana", "orange", "pear"};
        LinkedHashSet<String> set4 = new LinkedHashSet<>(Arrays.asList(fruits));
    }
}

In this example, set1 is an empty LinkedHashSet created using the default constructor. set2 is also an empty LinkedHashSet, but it has an initial capacity of 10. set3 is also an empty LinkedHashSet, but it has an initial capacity of 10 and a load factor of 0.5. Finally, set4 is a LinkedHashSet containing all the elements of the fruits array.

Java LinkedHashSet Example:

Here is an example that demonstrates how to use the LinkedHashSet class in Java:

import java.util.LinkedHashSet;

public class Main {
    public static void main(String[] args) {
        // Create a LinkedHashSet
        LinkedHashSet<String> set = new LinkedHashSet<>();

        // Add elements to the set
        set.add("apple");
        set.add("banana");
        set.add("orange");
        set.add("pear");

        // Print the set
        System.out.println("Set: " + set);

        // Check if the set contains an element
        if (set.contains("apple")) {
            System.out.println("The set contains 'apple'");
        } else {
            System.out.println("The set does not contain 'apple'");
        }

        // Remove an element from the set
        set.remove("orange");

        // Print the set after removal
        System.out.println("Set after removal: " + set);
    }
}

Output:

Set: [apple, banana, orange, pear]
The set contains 'apple'
Set after removal: [apple, banana, pear]

In this example, we create a LinkedHashSet object named set. We then add four elements to the set using the add() method. We print the set using System.out.println() to verify that all elements were added correctly.

Next, we check if the set contains the element “apple” using the contains() method. If the set contains “apple”, we print a message saying so. Otherwise, we print a message saying that the set does not contain “apple”.

We then remove the element “orange” from the set using the remove() method. We print the set again to verify that the removal was successful.

Java LinkedHashSet example ignoring duplicate Elements:

Here is an example that demonstrates how to use the LinkedHashSet class in Java to ignore duplicate elements:

import java.util.LinkedHashSet;

public class Main {
    public static void main(String[] args) {
        // Create a LinkedHashSet
        LinkedHashSet<String> set = new LinkedHashSet<>();

        // Add elements to the set (including duplicates)
        set.add("apple");
        set.add("banana");
        set.add("apple");
        set.add("orange");
        set.add("banana");

        // Print the set (duplicates are ignored)
        System.out.println("Set: " + set);
    }
}

Output:

Set: [apple, banana, orange]

In this example, we create a LinkedHashSet object named set. We add five elements to the set using the add() method, including two duplicates (“apple” and “banana”). When we print the set using System.out.println(), we can see that the duplicates are ignored and only one copy of each unique element is present in the set. This is because a LinkedHashSet does not allow duplicates.

Remove Elements Using LinkeHashSet Class:

You can remove elements from a LinkedHashSet in Java using the remove() method. The remove() method takes the element to be removed as an argument and returns true if the element was found and removed from the set, and false otherwise.

Here’s an example that demonstrates how to remove elements from a LinkedHashSet:

import java.util.LinkedHashSet;

public class Main {
    public static void main(String[] args) {
        // Create a LinkedHashSet
        LinkedHashSet<String> set = new LinkedHashSet<>();

        // Add elements to the set
        set.add("apple");
        set.add("banana");
        set.add("orange");
        set.add("pear");

        // Print the set before removal
        System.out.println("Set before removal: " + set);

        // Remove an element from the set
        boolean removed = set.remove("orange");

        // Check if the element was removed
        if (removed) {
            System.out.println("Removed 'orange' from the set");
        } else {
            System.out.println("'orange' was not found in the set");
        }

        // Print the set after removal
        System.out.println("Set after removal: " + set);
    }
}

Output:

Set before removal: [apple, banana, orange, pear]
Removed 'orange' from the set
Set after removal: [apple, banana, pear]

In this example, we create a LinkedHashSet object named set and add four elements to it using the add() method. We print the set before removal using System.out.println().

Next, we remove the element “orange” from the set using the remove() method. We check if the element was removed by inspecting the value of the removed variable. If the element was removed, we print a message saying so. Otherwise, we print a message saying that the element was not found in the set.

Finally, we print the set again using System.out.println() to verify that the element was removed successfully.

Java LinkedHashSet Example: Book

Here’s an example that demonstrates how to use the LinkedHashSet class in Java to store and retrieve Book objects:

import java.util.LinkedHashSet;

public class Main {
    public static void main(String[] args) {
        // Create a LinkedHashSet to store books
        LinkedHashSet<Book> books = new LinkedHashSet<>();

        // Create some Book objects
        Book book1 = new Book("The Catcher in the Rye", "J.D. Salinger", 1951);
        Book book2 = new Book("To Kill a Mockingbird", "Harper Lee", 1960);
        Book book3 = new Book("1984", "George Orwell", 1949);

        // Add the books to the set
        books.add(book1);
        books.add(book2);
        books.add(book3);

        // Print the set
        System.out.println("Books in the set:");
        for (Book book : books) {
            System.out.println(book);
        }

        // Check if the set contains a specific book
        Book searchBook = new Book("To Kill a Mockingbird", "Harper Lee", 1960);
        if (books.contains(searchBook)) {
            System.out.println("The set contains the book: " + searchBook);
        } else {
            System.out.println("The set does not contain the book: " + searchBook);
        }

        // Remove a book from the set
        books.remove(book2);

        // Print the set after removal
        System.out.println("Books in the set after removal:");
        for (Book book : books) {
            System.out.println(book);
        }
    }
}

class Book {
    private String title;
    private String author;
    private int year;

    public Book(String title, String author, int year) {
        this.title = title;
        this.author = author;
        this.year = year;
    }

    public String getTitle() {
        return title;
    }

    public String getAuthor() {
        return author;
    }

    public int getYear() {
        return year;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Book book = (Book) o;

        if (year != book.year) return false;
        if (!title.equals(book.title)) return false;
        return author.equals(book.author);
    }

    @Override
    public int hashCode() {
        int result = title.hashCode();
        result = 31 * result + author.hashCode();
        result = 31 * result + year;
        return result;
    }

    @Override
    public String toString() {
        return "Book{" +
                "title='" + title + '\'' +
                ", author='" + author + '\'' +
                ", year=" + year +
                '}';
    }
}

Output:

Books in the set:
Book{title='The Catcher in the Rye', author='J.D. Salinger', year=1951}
Book{title='To Kill a Mockingbird', author='Harper Lee', year=1960}
Book{title='1984', author='George Orwell', year=1949}
The set contains the book: Book{title='To Kill a Mockingbird', author='Harper Lee', year=1960}
Books in the set after removal:
Book{title='The Catcher in the Rye', author='J.D. Salinger', year=1951}
Book{title='1984', author='George Orwell', year=1949}

In this example, we create a `LinkedHashSet