my name is GYAN my name is GYAN - 3 months ago 14
Java Question

How 'before' and 'after' variables gets updated after call of put() method of LinkedHashMap?

LinkedHashMap
extends
HashMap
. Method
put()
is not present in
LinkedHashMap.java
code. So I consider that if I can call
put()
method in program below, then it must be inherited
put()
method from
HashMap
.

import java.util.*;
class First
{
public static void main(String[] args)
{
LinkedHashMap<Key, String> h=new LinkedHashMap<>(7);
h.put(new Key(3), "Hi");
h.put(new Key(1), "Hello");
h.put(new Key(9), "hru");
System.out.println(h);
}
}


Key.java is:

class Key
{
int i = 0;
Key(int i)
{
this.i=i;
}
public int hashCode()
{
return i;
}
public String toString()
{
return i+"";
}
}


It must have to maintain 'after' and 'before' references to preserve insertion order: http://a.disquscdn.com/uploads/mediaembed/images/3751/7481/original.jpg

But
put()
method in
HashMap
is not aware of these variables. Then how call on
put()
maintaining these variables?

I also cannot find
createEntry()
method in
HashMap
or
LinkedHashMap
code.

I am using:

java version "1.8.0_91"
Java(TM) SE Runtime Environment (build 1.8.0_91-b14)
Java HotSpot(TM) 64-Bit Server VM (build 25.91-b14, mixed mode)

Answer

There are callback methods called (indirectly) by HashMap operations such as put and remove which LinkedHashMap overrides :

// Callbacks to allow LinkedHashMap post-actions
void afterNodeAccess(Node<K,V> p) { }
void afterNodeInsertion(boolean evict) { }
void afterNodeRemoval(Node<K,V> p) { }

This allows LinkedHashMap to maintain a doubly linked list of entries, which HashMap knows nothing about.

Besides those methods, LinkedHashMap overrides newNode() to return an instance of LinkedHashMap.Entry, which contains before and after references.

EDIT :

Seeing your Keys class, it appears you forgot to override equals, which means you can add duplicate keys to your LinkedHashMap.