0

I was looking at the String.hashcode() function. It's defined as:

This method returns a hash code for this string. The hash code for a String object is computed as:

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

Using int arithmetic, where s[i] is the ith character of the string, n is the length of the string, and ^ indicates exponentiation. (The hash value of the empty string is zero.)

The question here is s[0] refers to the 0th character or rather the nth character in the string. But is it the int value of that character that is used to compute the hashcode?

1
  • is it the int value of that character that is used to compute the hashcode? Answer is YES. Commented Oct 11, 2013 at 3:47

2 Answers 2

2

Every char has a numeric value (ASCII/ UTF-16/ etc...). That is being use in this calculation e.g.

char x = 'A'; System.out.println(x * 2); // output is 130 

that is because numeric value of 'A' is 65

Sign up to request clarification or add additional context in comments.

1 Comment

Actually, it's not ASCII, but UTF-16 encoding of Unicode characters.
1

The smallest type Java execute arithmetic operations on is int. So s[0]*31^(n-1) is converted to ((int)s[0])*31^(n-1)

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.