Just curious, in String's hashCode implementation what is the reason behind extra references creation in a hashCode implementation (v 1.8.0_65):
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;
}
Taking into consideration that value
is final and created in constructor only (i.e. threadsafe) why do we need variable val[] reference here?
I.e. will this work:
public int hashCode() {
if (hash == 0 && value.length > 0) {
int h = 0;
for (int i = 0; i < value.length; i++) {
h = 31 * h + value[i];
}
hash = h;
}
return hash;
}
?
In addition to copying values from heap to stack to speed things up it is also about race conditions described in comments by @zapl. Which was not obvious to me before his comment.