I am new to Java and I am trying to learn about hash tables. I want to insert objects into my hash table and then be able to print all the objects from the hash table at the end. I am not sure I am doing doing this right because I have read that I need to override the get() method or hashCode() method but I am not sure why.
I am passing in String objects of student names. When I run the debugger after my inserts, it shows the key as “null” and the indexes of my inserts are at random places in the hash table. Ex. 1, 6, 10
This is how I have been adding. Can anyone tell me if this is correct and do I actually need to override things?
Thanks in advance!
CODE
Hashtable<String,String> hashTable=new Hashtable<String,String>();
hashTable.put("Donald", "Trump");
hashTable.put("Mike", "Myers");
hashTable.put ("Jimmer", "Markus");
You are doing things correctly. Remember, a
Hashtableis not a direct-access structure. You can’t “get the third item from aHashtable“, for example. There is no real meaning to the term “index” when you’re talking about aHashtable: numerical indexes of items mean nothing.A
Hashtableguarantees that it will hold key-value pairs for you, in a way that it will be very fast to conclude a value based on a key (for example: givenDonald, you will getTrumpvery quickly). Of course, certain conditions have to be fulfilled for this to work right, but for your simple String-to-String example, that works.You should read more about hash tables in general, to see how they really work behind the scenes.
EDIT (as per OP’s request): you are asking about storing
Studentinstances in your Hashtable. As I mentioned above, certain conditions have to be addressed for a Hashtable to work correctly. Those conditions are concerning the key part, not the value part.If your
Studentinstance is the value, and a simple String is the key, then there’s nothing special for you to do, because the String primitive already answers all of the conditions required for a proper Hashtable key.If your
Studentinstance is the key, then the following conditions must be met:Inside
Student, you must override thehashCodemethod in such a way that subsequent invocations ofhashCodewill return exactly the same value. In other words, the expressionx.hashCode() == x.hashCode()must always be true.Inside
Student, you must override theequalsmethod in such a way that it will only returntruefor two identical instances ofStudent, and returnfalseotherwise.These conditions are enough for
Studentto function as a proper Hashtable key. You can further optimize things by writing a betterhashCodeimplementation (read about it… it’s quite long to type in here), but as long as you answer the aforementioned two, you’re good to go.Example: