Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LinkedHashMap's impl - Uses Double Linked List, not a Single Linked List; Why

As I referred to the documentation of LinkedHashMap, It says, a double linked list(DLL) is maintained internally

I was trying to understand why a DLL was chosen over S(ingle)LL The biggest advantage I get with a DLL would be traversing backwards, but I dont see any use case for LinkedHashMap() exploiting this advantage, since there is no previous() sort of operation like next() in the Iterable interface..

Can anyone explain why was a DLL, and not a SLL?

like image 385
smc Avatar asked Oct 27 '12 02:10

smc


People also ask

Why is doubly linked list more useful than singly linked list?

Doubly linked list allows element two way traversal. On other hand doubly linked list can be used to implement stacks as well as heaps and binary trees. Singly linked list is preferred when we need to save memory and searching is not required as pointer of single index is stored.

Why LinkedHashMap uses doubly linked list?

The LinkedHashMap class is very similar to HashMap in most aspects. However, the linked hash map is based on both hash table and linked list to enhance the functionality of hash map. It maintains a doubly-linked list running through all its entries in addition to an underlying array of default size 16.

How is a doubly linked list different from a singly linked list?

Difference between Singly linked list and Doubly linked list. A Singly Linked has nodes with a data field and a next link field. A Doubly Linked List has a previous link field along with a data field and a next link field. In a Singly Linked List, the traversal can only be done using the link of the next node.

Why use a double linked list?

The most common reason to use a doubly linked list is because it is easier to implement than a singly linked list. While the code for the doubly linked implementation is a little longer than for the singly linked version, it tends to be a bit more “obvious” in its intention, and so easier to implement and debug.


1 Answers

It's because with an additional hash map, you can implement deletes in O(1). If you are using a singly linked list, delete would take O(n).

Consider a hash map for storing a key value pair, and another internal hash map with keys pointing to nodes in the linked list. When deleting, if it's a doubly linked list, I can easily get to the previous element and make it point to the following element. This is not possible with a singly linked list.

http://www.quora.com/Java-programming-language/Why-is-a-Java-LinkedHashMap-or-LinkedHashSet-backed-by-a-doubly-linked-list

like image 82
Neo M Hacker Avatar answered Sep 26 '22 17:09

Neo M Hacker