Originally Posted by
skillet
...Please tell me how to start calculating by hand....
Use the mathematical expression in the API reference to calculate the hashcode for "UEJ" as follows:
The decimal integer value of the char 'U' is 85.
The decimal integer value of the char 'E' is 69.
The decimal integer value of the char 'J' is 74.
The hashCode for this String is obtained by calculating the following:
((31 to the power 2) times 85) +
((31 to the power 1) times 69) +
((31 to the power 0) times 74)
With my handy-dandy calculator:
hashCode = 31*31*85 + 31*69 + 74 = 83898
For a Java hashCode "manual" calculator, I would use
Horner's nesting scheme to evaluate it.
For example:
//
// Illustration of String hashCode calculations
//
// Zaphod_b
//
class Z
{
public static void main(String [] args)
{
// Try the following for another example
//String testString = "This is a test string.";
// This is the one that I did "by hand."
String testString = "UEJ";
System.out.println("testString = " + testString);
int h1 = testString.hashCode();
System.out.println(" testString.hashCode() = " + h1);
int h2 = manualCalcHash(testString);
System.out.println(" manualCalcHash(testString) = " + h2);
} // End main()
static int manualCalcHash(String str) {
int result = 0;
for (int i = 0; i < str.length(); i++) {
result = result*31 + (int)str.charAt(i);
}
return result;
} // End manualCalcHash()
} // End class definition
Output:
testString = UEJ
testString.hashCode() = 83898
manualCalcHash(testString) = 83898
Note that arithmetic in this program, as well as the arithmetic in the String hashCode() method, is done with 32-bit integers. If the partial sums in the evaluation are larger than the value of a 32-bit integer, the resulting overflow is silently ignored in Java.
Try it again with testString set to something like "The quick brown fox jumps over the lazy dog." (I'm not going through that manually, but you can use my little example to show the results.)
Originally Posted by
skillet
.I never knew that the Object class had a method called hashcode.
It is entirely believable that one could spend a long, fruitful career writing Java code without ever encountering (much less having a need to know anything about) the String hashCode() method. But I recommend that when when you do "run across" such things, check with the Java API and see what it says. That's why I gave you the link in an earlier post.
I know that
seeing it is one thing but
understanding what is involved may be a head-scratcher, and that's why I like to see folks ask questions about things that they don't "get" at first glance (or even second glance).
Cheers!
Z