Sitemap
Bikash Sahani

Bikash Sahani

I'm passionated about teaching what textbooks don’t. Writing about Android, Kotlin, Jetpack Compose, architecture decisions & the trade-offs behind clean apps

Difference between HashSet vs LinkedHashSet

2 min readFeb 8, 2024
Press enter or click to view image in full size
Photo by Glenn Carstens-Peters on Unsplash

Both HashSet and LinkedHashSet are useful data structures in Java, but they differ in their key characteristics:

Get Bikash Sahani’s stories in your inbox

Join Medium for free to get updates from this writer.

Order:

  • HashSet: Does not maintain any order of elements. The order can be unpredictable and even change over time. Use this when order doesn’t matter.
  • LinkedHashSet: Maintains the insertion order of elements. Elements are iterated over in the same order they were added. Use this when preserving order is important.

Underlying Data Structure:

  • HashSet: Uses a hash table for storage, providing fast addition, removal, and search (constant time complexity: O(1)).
  • LinkedHashSet: Combines a hash table and a doubly-linked list. The hash table ensures uniqueness, while the linked list remembers the insertion order. This adds some overhead compared to HashSet.

Performance:

  • HashSet: Generally faster than LinkedHashSet due to its simpler structure.
  • LinkedHashSet: Slightly slower than HashSet, but the performance difference is usually negligible for most use cases.

Memory Usage:

  • HashSet: Requires less memory as it only uses the hash table.
  • LinkedHashSet: Requires more memory due to the additional linked list.

Use Cases:

  • HashSet: Use when you need to store unique elements efficiently and order doesn’t matter (e.g., checking for duplicate items).
  • LinkedHashSet: Use when you need to preserve the insertion order of unique elements (e.g., maintaining the order of items added to a shopping cart).

Additional Notes:

  • Both HashSet and LinkedHashSet allow only one null value.
  • LinkedHashSet inherits from HashSet, so it also has all the functionalities of HashSet.

I hope this explanation clarifies the differences between HashSet and LinkedHashSet.

Feel free to ask if you have any further questions!

--

--

Bikash Sahani
Bikash Sahani

Written by Bikash Sahani

I'm passionated about teaching what textbooks don’t. Writing about Android, Kotlin, Jetpack Compose, architecture decisions & the trade-offs behind clean apps