Now, I’m trying to understand how to construct the Hashtable.
The most interesting – as objects are added to the Hashtable?
I have read in a book that:
at first step:
Calculated hashCode() object.
Next, we determine the position of this object in the Hashtable: obj.hashCode() % Hashtable.length.
For example, add more elements to the Hashtable:
Hashtable<String, String> hm=new Hashtable<String, String>(100);
hm.put("Lee","Lee");
hm.put("lee","lee");
hm.put("eel","eel");
Define a bucket into which is placed the object:
System.out.println("Lee".hashCode() % 100);
System.out.println("lee".hashCode() % 100);
System.out.println("eel".hashCode() % 100);
If I understand the algorithm, the objects must be placed in the table as follows:
eel /*because,"eel".hashCode() % 100=0*/,
lee /*because, "lee".hashCode() % 100=20*/,
Lee /*because, "Lee".hashCode() % 100=68*/
but what we see as a result?
System.out.println(hm);
{Lee=Lee, lee=lee, eel=eel}
Please, tell me, where did I go wrong?
The iteration order of
Hashtable(as well asHashMap) elements is not guaranteed (implementation dependent), so IMHO there is not much point trying to build a theory on it. It may even change between different Java versions (it did change from Java5 to Java6).Btw
Hashtableis obsolete, it is recommended to use (and analyse)HashMapinstead.Your description sounds OK to me as a basic hash map implementation. However, the actual implementation of
HashMapis quite a bit more sophisticated than that, at least since Java4. E.g. the size of the hash table is always a power of two (which would be quite a bad decision for a basic hashtable like you describe), and hash values got from the key objects are rehashed internally to achieve a more even distribution over the actual size of the table. For more details on this, see the following issues of the Java Specialist Newsletter: