Understanding LinkedHashSet in Java: Characteristics and Usage

Summary of LinkedHashSet in Java

What is LinkedHashSet?

  • LinkedHashSet is a part of the Java Collections Framework.
  • It is an implementation of the Set interface that maintains a linked list of the entries in the set.
  • This linked list defines the iteration order, which corresponds to the order in which elements are inserted.

Key Characteristics

  • Unique Elements: Like all sets, it does not allow duplicate elements.
  • Insertion Order: It maintains the order of insertion, meaning that when you iterate through the set, elements will appear in the order they were added.
  • Performance: It provides constant time performance for basic operations (add, remove, contains).

Key Concepts

  • Inheritance: LinkedHashSet extends HashSet and implements the Set interface.
  • Null Values: It allows one null element.
  • Iteration: The iteration over a LinkedHashSet is predictable and follows the order of insertion.

Common Methods

  • add(E e): Adds an element to the set.
  • remove(Object o): Removes the specified element from the set.
  • contains(Object o): Checks if the specified element exists in the set.
  • size(): Returns the number of elements in the set.
  • clear(): Removes all elements from the set.

Example Code

import java.util.LinkedHashSet;

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

        // Adding elements
        linkedHashSet.add("Apple");
        linkedHashSet.add("Banana");
        linkedHashSet.add("Cherry");
        linkedHashSet.add("Apple"); // Duplicate, will not be added

        // Displaying elements
        for (String fruit : linkedHashSet) {
            System.out.println(fruit); // Outputs: Apple, Banana, Cherry
        }
        
        // Checking size
        System.out.println("Size: " + linkedHashSet.size()); // Outputs: Size: 3
    }
}

Conclusion

  • LinkedHashSet is a useful collection when you need to maintain the order of elements and ensure uniqueness.
  • It combines the features of both a HashSet (for fast access) and a linked list (for predictable iteration order).