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,201
  • 4
  • 54
  • 65
ZohebSiddiqui
  • 209
  • 3
  • 4
  • 14

1 Answers1

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.

Steven Pessall
  • 983
  • 5
  • 15