Understanding the Implementation of HashTable in JAVA
<p>I am trying to understand the implementation HashTables in JAVA. Below is my code:</p>

<pre><code>    Hashtable&lt;Integer, String&gt; hTab = new Hashtable&lt;Integer, String&gt;();
    hTab.put(1, "A");
    hTab.put(1, "B");
    hTab.put(2, "C");
    hTab.put(3, "D");

            Iterator&lt;Map.Entry&lt;Integer, String&gt;&gt; itr = hTab.entrySet().iterator();
    Entry&lt;Integer, String&gt; entry;

    while(itr.hasNext()){
        entry = itr.next();
        System.out.println(entry.getValue());
    }
</code></pre>

<p>When I run it, I get the below output:
                D
                C
                B</p>

<p>Which means that there has been a collision for the Key = 1; and as per the implementation:</p>

<p>"Whenever a collision happens in the hashTable, a new node is created in the linkedList corresponding for the particular bucket and the EntrySet(Key, Value) pairs are stored as nodes in the list, the new value is inserted in the beginning of the list for the particular bucket". And I completely agree to this implementation. </p>

<p>But if this is true, then where the hell "A" went when I try to retrieve the entrysets from the hashTable.</p>

<p>Again, I tried with the below code to understand this by implementing my own HashCode and equals method. And surprisingly, this works perfect and as per the HashTable implementation. Below is my code:</p>

<pre><code>public class Hash {

private int key;

public Hash(int key){
    this.key = key;
}

public int hashCode(){
    return key;
}

public boolean equals(Hash o){
    return this.key == o.key;

}

}

public class HashTable1 {

public static void main(String[] args) {
    // TODO Auto-generated method stub

    Hashtable&lt;Hash, String&gt; hTab = new Hashtable&lt;Hash, String&gt;();

    hTab.put(new Hash(1), "A");
    hTab.put(new Hash(1), "B");
    hTab.put(new Hash(2), "C");
    hTab.put(new Hash(3), "D");

    Iterator&lt;Map.Entry&lt;Hash, String&gt;&gt; itr = hTab.entrySet().iterator();
    Entry&lt;Hash, String&gt; entry;

    while(itr.hasNext()){
        entry = itr.next();
        System.out.println(entry.getValue());
    }
}
}
</code></pre>

<p>Output : 
       D
       C
       B
       A</p>

<p>Which is perfect. I am not able to understand this ambiguity in the behavior of HashTable in JAVA. Can somebody help me please.?</p>
