in Java when I say.
String str= "abcd";
str.hashCode();
My question is When is Hashcode calculated? @ line 1 or @ line 2?
I am assuming , that hashcode is pre-computed. Whenever string is updated hashcode would also 'perhaps' update.
or its the other way i.e. every time you call str.hashCode()
java computes its using the formula that's described here.
Consistency of hashCode() on a Java string
A code hash function always returns the unique hash value for every String value. The hashCode() method is the inherited method from the Object class in the String class that is used for returning the hash value of a particular value of the String type.
On strings, numbers and collection classes, hashCode() always returns a consistent value, apparently even across different JVM vendors.
Obviously, String. hashCode() isn't unique, but it can't be.
Strings can't be updated since they're immutable, and the value is cached after it's computed once:
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;
}
You cannot "update" a string. Strings are immutable. When you "change" a string instance, you actually get a new string instance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With