Exploring Java Collections – Understanding Linked HashSets

Exploring Java Fundamentals - Understanding Linked HashSets

A LinkedHashSet can be termed as a HashTable and LinkedList implementation of the Set interface, with a predictable iteration order. The difference between a HashSet and a LinkedHashSet is that the latter uses a doubly-linked list to maintain all of its entries. This link maintains the order of iteration of the elements, in the order in which they are inserted into the Set. And The insertion order doesn’t change if an already existing element is re-inserted into the set.

  1. LinkedHashSet maintains a doubly-linked List across all elements.
  2. It maintains insertion order
  3. It extends HashSet class and implements Set interface.
  4. Except insertion maintains, it inherit remaining all properties from HashSet

Constructors in LinkedHashSet:

  1. LinkedHashSet(): This constructor is used to create a default HashSet.
  2. LinkedHashSet(Collection C): Used in initializing the HashSet with the eleements of the collection C
  3. LinkedHashSet(int size): Used to intialize the size of the LinkedHashSet with the integer mentioned in the parameter.
  4. 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.
  5. 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

Example:

wp-content/uploads/2022/05/linkedhashset.png

Output:

true
true
false

Buy Me A Coffee

Found this article helpful? Please consider supporting!

Ram
Ram

I'm a full-stack developer and a software enthusiast who likes to play around with cloud and tech stack out of curiosity. You can connect with me on Medium, Twitter or LinkedIn.

Leave a Reply

Your email address will not be published. Required fields are marked *