Objects should provide what kind of value for these hash functions?

QUESTION

Objects should provide what kind of value for these hash functions?

A) The square root of the address in memory

B) A 32-bit integer

C) A java String

 

 

SUMMARY

Hash codes for a string in java would be given based on a formula that includes each and every character of the string and exponentiation with 31.

For primitive data types like int, float, and byte, the hash code would be their own binary representation.

In the case of an object, its hash code would be the internal memory address of the object.

 

 

EXPLANATION

For the given hash functions : 

A) 

Hash code for an object would be the internal memory address of the object.

The square root of the address of memory would be a number with the float data type. The hash code for this would again be the binary representation of it.

B)

For a 32-bit integer (4 bytes), the hash function would give the binary representation. The primitive data types like int, byte, and float have a binary representation. Therefore, the hash code for them will be the binary representation itself.

C) 

Let the java string to be s[n], where ‘n’= size of the string. Hash code is computed for the string with the formula given below:

Hash-code = s[0]*31^(n-1) + s[1]*31^(n-2) + s[2]*31^(n-3) + ……….. + s[n-1]

Where,

s[i] —–> ith character of the string ‘s’.

‘n’ ——> the size of the strings  

the symbol ‘^’ represents the exponentiation

Hash-code for the string s => “ball” 

= ASCII(‘b’)*31^(4-1) + ASCII(‘a’)*31^(4-2) + ASCII(‘l’)*31^(4-3) + ASCII(‘l’)*31^(4-4)

 

 

Also, read What is the problem with the following call to getHashTable?

 

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *