0

I have a problem here. I'm supposed to explain why my String "ab" returns 3105 when i use hashCode() on it.

My main problem is that i don,t understand which value i.e s[0] has.

s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]

Can someone explain it? Thanks.

5
  • This has all markings of an XY problem. What is the real problem you're trying to solve, and not the one you actually asked? Commented Apr 28, 2015 at 10:58
  • The real problem is the one i asked. In the formula given in Java API i dont know what value s[0] or s[1] should be. If i read from the formula - the s[0] should give me the value 1. Commented Apr 28, 2015 at 11:02
  • No, that's not your real problem. There is no reasonable "real problem" that involves the internal workings of Java's hashcode calculations. You must be trying to solve some other problem, and you think that messing around with hashcode formulas is the asnwer. It's not. Commented Apr 28, 2015 at 11:04
  • My task is to find the hashCode to the String "ab" by only reading the JAVA API and use the formula provided. Then i should test it and see if i got the answer right. Commented Apr 28, 2015 at 11:06
  • I would assume it holds the first character of the string you are passing, ie. the a from your ab string. Commented Apr 28, 2015 at 11:22

1 Answer 1

1

Assuming you have a string s = "ab".

  1. s[0] is the first letter of s, meaning "a" and so on.
    For a string with length of n, the last index will be n-1. i.e. the length of s is 2, the last letter of s is s[1] which is "b".
  2. Every letter in the ABC.. has a numerical ascii value that you can see in the ascii table.

The hash code for the string "ab" is

'a'*31^1+'b'*31^0 = 'a'*31+'b'*1 = 97*31+98*1 = 3105 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.