Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are String hashCode in java pre-computed?

Tags:

java

hashcode

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

like image 498
Arif Ali Saiyed Avatar asked Jul 10 '13 11:07

Arif Ali Saiyed


People also ask

Is hashCode of String always same?

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.

Is String hashCode consistent?

On strings, numbers and collection classes, hashCode() always returns a consistent value, apparently even across different JVM vendors.

Is String hashCode unique in Java?

Obviously, String. hashCode() isn't unique, but it can't be.


2 Answers

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;
    }
like image 61
Kayaman Avatar answered Oct 24 '22 16:10

Kayaman


You cannot "update" a string. Strings are immutable. When you "change" a string instance, you actually get a new string instance.

like image 36
Jan Dörrenhaus Avatar answered Oct 24 '22 16:10

Jan Dörrenhaus