Steven Rodeo wrote:
But why are the entries in the HashTable a Linked List ?. I am a lil confused.
It's a linked list for two reasons... (1) There isn't a bucket per hashcode. Many hashcodes share the same bucket. ie... it is possible to have more than one hashcode per bucket. (2) Just because two objects have the same hashcode, doesn't mean that they are equal. The list is required for two objects that hash to the same bucket -- but are not equal.
Maybe you've missed that what determines whether a key is already present in a HashMap is the equals method alone.
The hashCode method is used only as an aid to the HashMap in its efforts to store the entries efficient internally.
So equals and hashCode have two distinct and very different purposes. Equals guards the HashMap from multiple entries. HashCode helps the Hashmap with the internal organization.
Remember, according to the hashcode contract, "equal" instances must return the same hashcode. But it is not required that unequal objects return different hashcodes.
So in the context of a hashmap: Yes, multiple keys can certainly share the same hashcode. But in a map, each key must be unique (meaning not equal).
For example...
put(A, X);
put(B, Y);
...will result in two separate entries if A and B are not equal, regardless of whether A and B have the same hashcode. On the other hand, if A and B are equal, then this will result in only one entry, because keys must be unique, so (B, Y) will replace (A, X).
"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer sscce.org