Here what is written in String API for Hashcode------
public int hashCode() {
int h = hash;
if (h == 0 && value.length > 0) {
But how this happens for two string created with new like :
String a = new String("abc"); String b = new String("abc");
It doesn't happen. Caching only occurs for a single String
object.
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;
}
For a single String
, hash
is where the hash code is stored. If it's 0
, then it recomputes it -- storing it in the local variable h
-- and once the hash code is newly computed, it's stored back in hash
so it can be used in the future.
If String
s were mutable, then the stored hash code would be wrong after the string got changed, so any way of changing the string would have to reset hash
to 0
to indicate it had to be recomputed anew. That gets messy, though, on many many different levels, which is why String
is not mutable.