I have a class called Node that I’ve written. I overrode the hashCode() function of it to take into account two fields of the Node (there is also a third field which doesn’t affect the my hashCode() function). I also wrote an equals() function which takes all three fields into account.
I’m trying to use the Hashtable class to store Nodes so that I can easily check later on when I make new nodes whether the new nodes are duplicates of ones in the hashtable or not. So far I have this
Hashtable<Node,Node> hashTbl = new Hashtable<Node,Node>();
...
Node node1 = // some new node
hashTbl.put(node1,node1);
...
So now, say I make a new node called node2 which has the exact same hash value as node1, but is not equal to node1 as defined by the equals() method. I want to check whether node2 is a duplicate of anything in the hash table (it’s not), but if I use constainsKey(), won’t that give me a false positive? It seems like using containsValue() wouldn’t be utilizing the efficiency of the hash table. So how can I do this efficiently?
Also, my assumption is that when I call hashTbl.put(arg1,arg2), it calls the hashCode() function of arg1 and uses that value to find an index in an “array” to place arg2 in. Is this right?
Sorry for being kind of confusing. Thanks anyone.
First, you probably want a HashSet (or something similar), not a Hashtable – all you are trying to do is check for membership, and a HashSet will allow you to do that without needing to provide a value for every key.
To answer your question, the determines which slot in the array that the value gets put in, but every slot is actually a linked list. If the new key is not
.equalto any other key in the linked list, the new key and value are put in their own node in the linked list. Simply returning 1 for all objects is a perfectly legal and correct.hashcodeimplementation. The only issue with that implementation is that it turns Hashtables and similar data structures into linked lists (which obviously causes you to lose all the performance benefits of the Hashtable).In short, your
.hashcodemethod will work fine. If you put a large number of objects that aren’t.equalbut have the same hashcode, performance will decrease, but the code will still function correctly.