6

As HashMap uses LinkedList when two different keys produces a same hashCode.But I was wondering what makes LinkedList a better candidate here over other implementation of List.Why not ArrayList because ArrayList uses Array internally and arrays have a faster iteration compared to a LinkedList.

3 Answers 3

12

Collisions in hash maps are an exception, rather than a rule. When your hash function is reasonably good, as it should be, there should be very few collisions.

If we used ArrayList for the buckets, with most lists being empty or having exactly one element, this would be a rather big waste of resources. With array lists allocating multiple members upfront, you would end up paying forward for multiple collisions that you may not have in the future.

Moreover, removing from array lists is cheap only when the last element gets deleted. When the first one gets deleted, you end up paying for the move of all elements.

Linked lists are free from these problems. Insertion is O(1), deletion is O(1), and they use exactly as many nodes as you insert. The memory overhead of the next/prior links is not too big a price to pay for this convenience.

Sign up to request clarification or add additional context in comments.

3 Comments

Of course you can make deletion simpler in an array-based structure by using a deletion placeholder, but that comes at a price: insertion becomes O(n). You can avoid that too, but there's a price for that too: more space wasted. The moral of the story is that nothing is free.
Why not use AVL trees instead of linked lists? AVL trees have a worst case lookup, insertion and deletion time of log(n), instead of the O(n) worst case lookup for the linked list. I understand that AVL trees are not really required because the data does not need to be sorted, but wouldn't they would be more efficient anyway?
The Linked List insert from end is O(1), from element is o(n) @Sergey Kalinichenko
3

The problem with an arrayList is that you can't fast remove an element: you have to move all the elements after the one you remove.

With a linkedList, removing an element is merely changing a reference from one node to the new next one, skipping the removed one.

The difference is huge. When you want to have a list and be able to fast remove elements, don't use an arraylist, the usual choice is the linked list.

Comments

3

Why not ArrayList because ArrayList uses Array internally and arrays have a faster iteration compared to a LinkedList.

And ArrayList is much slower to modify. So they made a judgement call and went with LinkedList.

1 Comment

Oh I completely overlooked the removal part.Thanks for the answer...:)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.