Remember that hashCode doesn't always generate a unique number. It is a non-unique calculation. For the most part, hashCode gives a unique number, but there is a small chance that calling hashCode on two different objects will generate the same value. That's why you then need to go to the equals method - to see if two objects that create the same hashcode are really equal to each other, as opposed to just curiously generating the same hash.
For the JVM, comparing numbers is much easier than calling equals, so calling hashCode all the time is much faster. Only going to equals when needed, should really speed things up.
I have a bunch of sample mock questions on the hashCode and equals contract on my blog right now. There's about 15-20 sample exam questions on the topic designed to drive home the point. Give them a try!
Sample SCJP 6.0 Mock Exam Questions: Collection Classes and hashCode
Given the following code, what would be the result of running the HashTest class?
public class HashTest{
public static void main (String args[]){
java.util.Hashtable hashtable = new java.util.Hashtable();
hashtable.put(new Entity(1), new Entity(1));
hashtable.put(new Entity(2), new Entity(2));
hashtable.put(new Entity(3), new Entity(3));
System.out.println(hashtable.size());
}
}
/**** Entity Class ****/
class Entity{
public final int CODE = 007;
int id;
Entity(int id) {this.id = id;}
public int hashCode() {return id;}
public boolean equals(Object o) {return true;}
}
a) 0 is printed to the console
b) 1 is printed to the console
c) 2 is printed to the console
d) 3 is printed to the console
e) compile time error
f) runtime error
Option d) is correct.
In this case, the equals method always returns true, but if the hashcode method indicates that two instances are NOT the same, the equals method does not need to be called. As a result, the HashMap treats every Entity key as a unique entity or instance, despite the fact that all three instances would actually generate a true value when compared using the equals method.
Since the key values appear unique to the JVM using the HashMap and the hashcode method of the entities, each key being used by the HashMap is considered unique.
-Cameron McKenzie