Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LinkedHashMap vs HashMap != LinkedList vs ArrayList

I have read that LinkedHashMap has faster iteration speed than HashMap because its elements are doubly linked to each other. Additionally, because of this, LinkedHashMap is slower when inserting or deleting elements. Presumably because these links also need to be updated.

Although I can see an analogy to LinkedList vs ArrayList, in that the elements of LinkedList are also doubly-linked, I read that it iterates slower than ArrayList, and has faster insertion and deletion times.

Why is this? Perhaps I am making a mistake somewhere?

Cheers!

like image 434
Markos Fragkakis Avatar asked Mar 08 '10 21:03

Markos Fragkakis


People also ask

Which is better LinkedHashMap or HashMap?

HashMap as do not maintain any insertion order of its elements hence is faster as compare to TreeMap also do not sort its elements on the basis of its value so also faster than LinkedHashMap. LinkedHashMap is faster as compare to TreeMap but is slower than HashMap.

Which is better HashMap or ArrayList?

ArrayList stores the elements only as values and maintains internally the indexing for every element. While HashMap stores elements with key and value pairs that means two objects. So HashMap takes more memory comparatively.

What is the difference between ArrayList and HashMap?

The difference between ArrayList and HashMap is that ArrayList is an index-based data-structure supported by array, while the HashMap is a mapped data structure, which works on hashing to retrieve stored values. Although both are used to store objects, they are different in their implementation, function, and usage.

Is HashMap faster than LinkedList?

LinkedHashMap, however, is the same data structure as a HashMap but with a LinkedList woven into it to make iteration faster and consistent. The reason that LinkedHashMap iteration is faster than HashMap iteration is that HashMap iteration has to iterate over all of the buckets, even the empty ones.


1 Answers

The analogy does not work. LinkedList and ArrayList are two unrelated implementations of a List. LinkedHashMap, however, is the same data structure as a HashMap but with a LinkedList woven into it to make iteration faster and consistent.

The reason that LinkedHashMap iteration is faster than HashMap iteration is that HashMap iteration has to iterate over all of the buckets, even the empty ones. The the fact that LinkedHashMap has a list pointing to the data means that it can skip the empty buckets. The list in the LinkedHashMap is a linked list because removal times remain constant (rather than O(n) if it was some arrray-backed list).

like image 142
ILMTitan Avatar answered Oct 10 '22 04:10

ILMTitan