Problem Description
While reading Oracle documentation about Hashtable I found that "in the case of a "hash collision", a single bucket stores multiple entries, which must be searched sequentially", so I try to find method which will return me items sequentially, if I have two items with the same hash, but can't find in the documentation. In order to reproduce this situation I try to write a simple code, which you can find below.
Oracle Documentation about Hashtable
An instance of Hashtable has two parameters that affect its performance: initial capacity and load factor. The capacity is the number of buckets in the hash table, and the initial capacity is simply the capacity at the time the hash table is created. Note that the hash table is open: in the case of a "hash collision", a single bucket stores multiple entries, which must be searched sequentially. The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased. The initial capacity and load factor parameters are merely hints to the implementation. The exact details as to when and whether the rehash method is invoked are implementation-dependent.
Simple Code
class Key {
public final int mID;
public Key(int id) {
mID = id;
}
@Override
public int hashCode() {
if(mID == 1 || mID == 2) {
System.out.println("Have same hashCode()");
return 5673654;
}
return super.hashCode();
}
};
public class HashtableTest {
public static void main(String... args) {
Hashtable<Key, String> dict = new Hashtable<Key, String>();
dict.put(new Key(1), "One");
dict.put(new Key(2), "Two");
System.out.println(dict.size()); // Prints 2
System.out.println(dict.get(new Key(1))); // Prints null
}
};
In the code above I try to add to the Hashtable two items which have same hashcode (anyway I think that they have :) ), so for that I create my Key
class and override it's hashCode
method, but this was useless as I can't even get item from the Hashtable and I think that items are not added sequentially.
Questions
- How I can simulate situation of stores multiple entries in one bucket? (In order to more deeply understand how this work)
- How I can access to the items in the Hashtable which are stored sequentially?