|
-
February 16th, 2009, 07:13 PM
#1
custom hashCode() method outputs integers DIFFERENT than the String class
Here is my code; the algorithm is taken from the Java API here
Code:
public int hashCode()
{
int code = 0;
for (int i = 0; i < length; i++) // where length is the length of the string.
code += chars[i]*Math.pow(31, length - 1 - i); // where "chars" is a char array.
return code;
}
A quote from the previously-linked API page on the String class:
Returns a hash code for this string. The hash code for a String object is computed as
s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
As you can see, I used this algorithm correctly. However, the outputs are still different. Consider these outputs (where my custom implementation of a String is called MyString) (you can verify them yourself if you wish...):
(new MyString("WHAT")).hashCode() returns 2663108
(new String("WHAT")).hashCode() returns 2663108
(new MyString("HOWEVER")).hashCode() returns 2147483647
(new String("HOWEVER")).hashCode() returns 1819945294
(new MyString("ABSOLUTELY INCORRECT")).hashCode() returns 2147483647
(new String("ABSOLUTELY INCORRECT")).hashCode() returns -1874695255
Ok, if you haven't already noticed (I just did), for some reason the integer returns is the same for "HOWEVER" and "ABSOLUTELY INCORRECT". I have no idea why; the odds seem unlikely.
Hold on, isn't 2147483647 the largest positive integer? Is there some sort of cap that is imposed on the add function when the result overflows?
And this leads me to ask ... How can I emulate the String class correctly, to provide overlap so that the addition overflows to negative integers (as I know they will, since we all do math with a 2's-complement system).
Last edited by Nim; February 16th, 2009 at 07:18 PM.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|