Write a program which computes the hash of a string, and the hash of two integers.

Write a program which computes the hash of a string, and the hash of two integers.  The formula for the hash is the same in both cases, except in the case of the string, you will have a variable number of characters.

To compute the hash Java uses, first set the hashCode to 0.  Starting at the beginning of the string, go through the string character by character.  For each character, multiply the previous hash by 31 and then add the character.  This should produce exactly the same value as String.hashCode().

Your string hash method should have the declaration

public static int hashCode(String str)

In your program, set a string = “ABCDEFGHIJ”, compute the hash with your hashCode method and compare it with the String.hashCode() value.  If the two are equal, print out “Hashes are equal”.  If the are not the same, print “Hashes are not equal”.

For the hash of two integers, use the following formal declaration

public static int hashCode(int n1, int n2)

Use the formula for computing hashes shown above for strings, but only compute the first two terms using n1 and n2 successively.  Compute the hash of the hash of the above string and the number 123456789.  You should get -207560432 as an answer.

 

"Is this question part of your assignment? We Can Help!"

Essay Writing Service