This week, let's start right off with a mock exam question. Try this one on for size:
Which of the following methods are legal hashCode methods (by legal, I am not talking about syntax, but the ability to return a hashCode that complies to the "general contract" of Java hashCodes)?
public int hashCode()
{
return 0;
}
public int hashCode()
{
return (int)(Math.random() * Integer.MAX_VALUE);
}
A. The first method.B. The second method. C. Both methods. D. Neither method. |
So what's the answer? It's A, of course. Only the first method provides legal hashCode values. Granted, they're probably not the greatest hashCode values in the world, but they're still legal.
Here are the rules that hashCode values must abide by. You can find these in the Java API Spec for Object.
Note that the second method shown above fails to meet both criteria 1 and 2. It does not guarantee that the hashCode method will always return the same value and it does not guarantee that two "equal" objects will have the same hashCode.
Meanwhile, the first method, which always returns the number 0 does meet both of those criteria. That makes it a "legal" hashCode method.
So what makes method 1 undesirable? If you read the final line of criteria 3, you'll notice this: "However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables." Producing the same value for all objects, as the first method does, may hinder the performance of hashtables. They'll still work - they just won't work as well. In fact, by using the first method as your hashCode method, you'd destroy the entire purpose of using a hashtable and essentially turn a hashtable into an ordinary list (because everything would be stored in one big list under the same hash value).
The hashCode method defined in Object converts the internal address of the object in question to an int to provide its hashcode value. In general, this works well, but it is not required. There are a number of objects that override hashcode to provide better values (Integer is a great example).
The rules for hashCodes are pretty simple - just keep them in mind when taking the SCJP exam.
Corey
Integer i = new Integer(-10);
System.out.println(i.hashCode());
This code produces -10 as an output, which proves that a valid hashCode value can be negative.
