Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How linkedhashmap maintains insertion order

Tags:

java

hashmap

I know how Hashmap works internally. Linkedhashmap is extending Hashmap class. So how Linkedhashmap is able to maintain the insertion order. I have read the javadoc for Linkedhashmap, but it does not have any details about this. Can somebody help me understand this?

Thanks in advance.

like image 573
Newbie Avatar asked Nov 24 '13 06:11

Newbie


1 Answers

http://docs.oracle.com/javase/7/docs/api/java/util/LinkedHashMap.html.

Idea behind implementation is quite simple. It extends regular hashMap (so it has all hashMap goodies) but also builds double linked list when adding elements.

(entries are also extended from the HashMap.Entry so they have pointers to after and before) So all entries are ordered HEAD -> Entry1 <-> Entry2 ... <-- TAIL

and at the same time kept in standard HashSet (i assume you are familiar with implementation).

Now when iterating It Linked list of entries is used.

like image 148
Daber Avatar answered Nov 14 '22 04:11

Daber