0

I was seeing the source code of LinkedHashMap ,when the instance of LinkedHashMap is created it first it creates header, and when a new entry is added into the LinkedHashMap it adds the particular entry before the header, I am not able to understand these line of code

 private void addBefore(Entry<K,V> existingEntry) {
 after = existingEntry;
 before = existingEntry.before;
 before.after = this;
 after.before = this;
 }

what I have understood is that after pointer is pointing to the header always as i can see and before pointer is pointing to the entry before existingEntry can anybody explain me this code and how it maintain the pointer after and before.

giannis christofakis
8,3424 gold badges56 silver badges67 bronze badges
asked Mar 26, 2014 at 10:52

1 Answer 1

1

The code you posted is called when you are inserting a new Entry into the List. I guess it is best explained with an example.

Let's assume you have two entries A and B, where A is before B. In this case these Entries have the following values:

A.before = B
B.after = A

Now you want to insert a new Entry X between the two. In this case the method you posted is called for X. After its execution you have the following values:

A.before = X
X.after = A
X.before = B
B.after = X

The method addBefore() not only needs to set the after and before members of the new Entry, it also needs to update the references in the linked members.

answered Mar 26, 2014 at 11:05

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.