0

I came across the below in the JAVA docs related to the LinkedHashSet:

Hash table and linked list implementation of the Set interface, with predictable iteration order.

But If I see the source of LinkedHashSet I am not able to find any implements/extends related to HashTable or LinkedList. Then how does it inhibits the features of both these data structures?

ghostrider
  • 2,046
  • 3
  • 23
  • 46

1 Answers1

2

It does not inherit from those classes, or use them in any way.

But you could write your own linked list class, and it would still be a linked list, even if it had no relationship to java.util.LinkedList. That's how LinkedHashSet works: it does not use java.util.Hashtable, nor java.util.LinkedList, but it has an implementation of the data structures nonetheless.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
  • But it does not have any implementations related to add, remove etc. It uses all these of HashSet. Then how is it having those characteristics of linkedlist and hashtable? – ghostrider Dec 26 '19 at 19:20
  • 2
    `HashSet` actually has the "linked" implementation in it, for simplicity of implementation; `LinkedHashSet` just uses special superconstructors to activate that behavior. (`HashSet` is actually just built on top of a `HashMap`, and `LinkedHashSet` on a `LinkedHashMap`.) – Louis Wasserman Dec 26 '19 at 19:23
  • HashSet is built on top of Hashmap, this can be verified from the code of HashSet constructor. How to verify if LinkedHashset is built on top of LinkedHashMap in the same way through the code? – ghostrider Dec 26 '19 at 19:38
  • 1
    @ghostrider Track the superconstructor invoked by LinkedHashSet. – Louis Wasserman Dec 27 '19 at 20:03
  • Thank you @LouisWasserman , this was driving me crazy. no way I could have figured out by myself, without spending a lot of time debugging this. Basically this is the constructor called by LinkedHashSet from HashMap class - `HashSet(int initialCapacity, float loadFactor, boolean dummy) { map = new LinkedHashMap<>(initialCapacity, loadFactor); }` It seems strange why HashSet class knows about LinkedHashMap in the first place and then also initialises it's object. – Yash Agarwal Jul 24 '20 at 18:36