kirkegaard
kirkegaard

Reputation: 1138

String and Hashcode need explanation

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.

Upvotes: 0

Views: 88

Answers (1)

motcke
motcke

Reputation: 437

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

Upvotes: 1

Related Questions