Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LinkedHashMap vs HashMap, LinkedHashSet vs HashSet

I know the difference between all of them and I understand that LinkedHashMap and LinkedHashSet provide an insertion-ordering. I understand that LinkedHashMap extends HashMap and LinkedHashSet extends HashSet.

Why don't we always use LinkedHashMap instead of HashMap and why don't we always use LinkedHashSet instead of HashSet?

like image 415
O Connor Avatar asked Dec 20 '22 13:12

O Connor


2 Answers

Keeping the insertion order has its associated costs, both in terms of needing more memory, and spending additional CPU cycles:

  • You need additional memory to keep the extra links,
  • You need additional CPU cycles to maintain it.

Although the asymptotic complexity is the same, the added convenience does not come for free. If you do not need the insertion order maintained, you do not have to "pay" for it, and use lighter-weight HashSet<E> and HashMap<K,V> instead.

like image 145
Sergey Kalinichenko Avatar answered Jan 09 '23 01:01

Sergey Kalinichenko


Ordering is brought at the cost of efficiency in LinkedhashMap / LinkedHashSet. So, whenever we don't need Ordering, we could use hashMap / HashSet.

like image 29
TheLostMind Avatar answered Jan 08 '23 23:01

TheLostMind