KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
I've been investigating the hashCode() methods in java and found the one for String class strange. The source code is as follows: public int hashCode() { int h = hash; if (h == 0 && value.length > 0) { char val[] = value; for (int i = 0; i < value.length; i++) { h = 31 * h + val[i]; } hash = h; } return h; } The code itself is quite straight forward. But I wonder what's the reason for calculating hash code this way? Why choose 31? Why start from 0 instead of value.length - 1? Any guarantee that this would make hashcodes less possible to collide with each other?
Tags (comma-separated)
Save Edits
Cancel