How linkedhashmap maintains insertion order

喜夏-厌秋 提交于 2020-12-29 06:31:38

问题


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.


回答1:


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.




回答2:


It maintains a linkedlist of the entries in the map in the order in which they were inserted. This helps to maintain iteration order and elements will be returned in the order they were first added in.

You would like reading this post too as whenever you start comparing, you might understand better: Difference between HashMap, LinkedHashMap and TreeMap




回答3:


Internally it maintains double linked list (Map.Entry) to store objects in the order , because double linked list stores the address of previous node and next node .

Same you can also check in source code .




回答4:


The reference fields before and after maintains a doubly linked list for all the entries of the LinkedHashMap. Using before and after fields, we can traverse all the entries of a LinkedHashMap.
Internal of LinkedHashMap : http://techmastertutorial.in/java-collection-internal-linked-hashmap.html



来源:https://stackoverflow.com/questions/20171999/how-linkedhashmap-maintains-insertion-order

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!