💻

Understanding LinkedHashSet in Java

Feb 1, 2025

Lecture Notes: LinkedHashSet in Java

Introduction

  • Topic: Understanding the concept of LinkedHashSet in Java.
  • Context: Builds on previous discussions about the Collection interface and its child interfaces and classes.
    • Collection Interface: Root interface of all collections.
    • Set Interface: Child interface of Collection.
    • Classes Implementing Set: HashSet and LinkedHashSet.

LinkedHashSet vs. HashSet

Similarities

  • Both HashSet and LinkedHashSet implement the Set interface.
  • Neither allows duplicate elements.
  • Both can configure initial size and load factor (default is 16 and 0.71 respectively).

Differences

  • HashSet:
    • Insertion order is not preserved (elements are stored in random order).
    • Underlying data structure: Hash Table.
  • LinkedHashSet:
    • Preserves insertion order (elements are stored in the order they are inserted).
    • Underlying data structure: Combination of Hash Table and Linked List.

Implementation Details

Creating a LinkedHashSet

  • Declaration: LinkedHashSet<Integer> lSet = new LinkedHashSet<>();
    • Can specify data type to store similar types of objects (e.g., Integer).
    • Can opt for storing different types without specifying a data type.

Adding Elements

  • Use the add method to insert elements.
    • Example: lSet.add(100); for inserting integers.
  • Properties:
    • Duplicates are not allowed.
    • Insertion order is preserved.

Demo

  • HashSet Behavior:
    • Random element order upon printing.
    • Example output may differ from insertion order.
  • LinkedHashSet Behavior:
    • Maintains insertion order upon printing.
    • Demonstrates the key difference in maintaining order.

Methods

  • Methods available in HashSet are also applicable to LinkedHashSet:
    • add, addAll, remove, removeAll, contains, and containsAll.

Conclusion

  • Core Understanding: LinkedHashSet is primarily distinguished from HashSet by its ability to preserve the insertion order of elements.
  • Practical application of LinkedHashSet is demonstrated through code examples using Eclipse IDE.

This concludes the lecture on LinkedHashSet in Java.