简体   繁体   中英

Are String hashCode in java pre-computed?

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 ie every time you call str.hashCode() java computes its using the formula that's described here .

Consistency of hashCode() on a Java string

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.

You can't update existing String instance as String is immutable . What you will be able to do is create a new instance and assign it to the same variable.

String.hashCode() method is fired only when you call it, just like any other method you write or use in Java.

So, to answer your question, the hashcode is not calculated when the String is created.

If you see the hashcode method, it's written to calculate only once and saves the precalculated hashcode value to a local variable hash

public int hashCode() {
 int h = hash;
 if (h == 0) {
  int off = offset;
  char val[] = value;
  int len = count;
  for (int i = 0; i < len; i++) {
   h = 31*h + val[off++];
  }
  hash = h;
}
return h;
} 

So, the hashcode is calculated only when the method is called

For most strings, the hash value will be computed the first time hashCode() is called or--in multi-threaded scenarios--every time it's called until one of the calls manages to compute and cache its value. String instances containing sequences of characters whose hash code evaluates to zero, however, will have their hash values computed every time hashCode() is called upon them. Note that it would have been possible to avoid such redundant computation by using a hash function which would never return zero for non-trivial strings (eg by adding the line if (!h) h=value.length+1; ), but changing Java to do that now could potentially--at least in theory--break some existing code that assumes that any sequence of characters for which the built-in string hashCode() has ever yielded zero will continue to do so until the end of time.

Because writing to a variable of type String simply overwrites the contained reference without affecting the instance of String to which it had previously referred, nothing related to that previous string's hash-code (including whether or not its value has yet been computed) will be affected by the assignment.

I see this question is still "not answered". Found it by googling. So to summarize all answers and add some more value:

  • hashCode for Strings are cached on the first call to this function, there is an internal field hashCode which is zero initialized
  • Strings are immutable, but you can change them using Reflection API. Still the cached hashCode will not be updated automatically
  • Strings that initialized by character constants are always interned, so if you will write

     public static void main(String[] args) { String hello1 = "Hello"; String hello2 = "Hello"; System.out.println( hello1 == hello2 ); } 

you can be sure it will print out "true". if you will call for hashCode of hello1 and hello2 the hashCode will be calculated only once, since it is actually same object.

hope this information will be usefull for those who arrive there by googling.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM