Though its not such a practical thing that would be needed in daily practices of coding, yet we are going to cover this part of String because its been asked by many interviewers now a days and can also be used in some situations while coding where it requires to calculate the hashcode and the developer needs some further operations on the calculated hashcode.
Well, we have a simple formula for calculating the hashcode of any String manually and that is :
hashcode = s[0]*31^(n-1) + s[1]*31^(n-2) + ......................+s[n-1].
Here, s[0], s[0] ...s[n-1] are the ASCII values of the characters occurring in the String. n is the length of the String.
For example:
Let us suppose, we have a String like follows.
String str = "ab";
and we run str.hashcode() then it will produce the output as 3105. Here is how it comes,
hashcode = ASCII(a)*31^(1) + ASCII(b);
= 97*31+98=3105.
And this is the reason why the hashcode of space(" ") is equal to the ASCII value of space (" ").
Also, the same reason why the hashcode of empty string is ZERO.
That's it. Kindly, post in the comments if you have any questions or queries regarding this. Happy learning.
Well, we have a simple formula for calculating the hashcode of any String manually and that is :
hashcode = s[0]*31^(n-1) + s[1]*31^(n-2) + ......................+s[n-1].
Here, s[0], s[0] ...s[n-1] are the ASCII values of the characters occurring in the String. n is the length of the String.
For example:
Let us suppose, we have a String like follows.
String str = "ab";
and we run str.hashcode() then it will produce the output as 3105. Here is how it comes,
hashcode = ASCII(a)*31^(1) + ASCII(b);
= 97*31+98=3105.
And this is the reason why the hashcode of space(" ") is equal to the ASCII value of space (" ").
Also, the same reason why the hashcode of empty string is ZERO.
That's it. Kindly, post in the comments if you have any questions or queries regarding this. Happy learning.
No comments:
Post a Comment