10

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.

5

4 Answers 4

9

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.

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

Comments

1

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

Comments

0

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 .

Comments

0

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

Comments

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.