Last Updated: 22 January, 2023
HashSet and LinkedHashSet are both implementations of the Set interface, contain unique elements, and accept only one NULL as an element. LinkedHashSet is a child class of the HashSet class.
There are many differences between the HashSet and LinkedHashSet that are given below.The HashSet class is a member of the Java Collection Framework. HashSet was introduced in the JDK 1.2 version and is available in the java.util package.
A HashSet is used to create an unordered collection of elements that contains only unique elements; no duplicate elements are allowed. The HashSet provides constant-time performance for general operations such as add, remove, contain, size, etc.
HashSet's internal implementation is based on the hash table for creating and storing a collection of unique elements.
Java HashSet Class Declaration
Here, E defines the type of elements that the Set will contain.
Java HashSet important features:
The LinkedHashSet class of the Java collections framework was introduced in the JDK 1.4 version and is available in the java.util package.
LinkedHashSet is the Hashtable and linked list implementation of the Set interface with preserved iteration order. The linked list defines the iteration order, which is the order in which elements are inserted into the set. Insertion order is not affected if an element is re-inserted into the set.
LinkedHashSet is a child class of HashSet, so it has all the functionalities of the HashSet class. The HashSet does not maintain the insertion order of elements, whereas the LinkedHashSet maintains the element insertion order. This one is the main difference between both.
Java LinkedHashSet Class Declaration
Here, E defines the type of elements that the Set will contain.
Java LinkedHashSet important features:
HashSet | LinkedHashSet |
---|---|
The underlying data structure is a hash table. | The underlying data structure is a hash table + linked list (doubly linked list). |
Insertion order is not preserved. | Insertion order is preserved. |
HashSet requires less memory than the LinkedHashSet. | LinkedHashSet requires more memory than the HashSet. |
HashSet is a parent class of LinkedHashSet. | LinkedHashSet is a child class of HashSet. |
Introduced in JDK 1.2 Version. | Introduced in JDK 1.4 Version. |
Output
HashSet elements: [800, null, 500, 200]
Output
LinkedHashSet elements: [800, 500, null, 200]
That's all guys, hope this Java article is helpful for you.
Happy Learning... 😀
feedback@javabytechie.com