Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is hash code of java.lang.String really cached?

String s1 = "String1";      
System.out.println(s1.hashCode()); // return an integer i1 


Field field = String.class.getDeclaredField("value");  
field.setAccessible(true);  
char[] value = (char[])field.get(s1);  
value[0] = 'J';  
value[1] = 'a';  
value[2] = 'v';  
value[3] = 'a';  
value[4] = '1'; 
System.out.println(s1.hashCode()); // return same value of integer i1 

Here even after I changed the characters with the help of reflection, same hash code value is mainatained.

Is there anything I need to know here?

like image 897
Saurab Parakh Avatar asked Jan 08 '14 16:01

Saurab Parakh


People also ask

Are string hashes cached?

It is cached in a private int field in the string itself. It doesn't make any difference that different Strings may have the same hashcode ... because the hashcode is stored in the respective String objects.

Is hashCode cached?

Normally, a hashCode is calculated every time you call the hashCode() method. That's usually not a problem, since the calculation is usually not very complex. Sometimes, however, a hashCode needs to be cached for performance reasons.

How good is Java string hashCode?

hashCode() is poor as most prime numbers between 26 and 256 would have been a better choice than 31. The nearest prime 29 is likely to be better and 109 might be even better. A more extensive study of a range of use cases would be needed to settle on one number better in most cases.

What is hashCode of string in Java?

Java String hashCode() Method The hashCode() method returns the hash code of a string. The hash code for a String object is computed like this: s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]


1 Answers

A String is meant to be immutable. As such, there is no point having to recalculate the hashcode. It is cached internally in a field called hash of type int.

String#hashCode() is implemented as (Oracle JDK7)

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;
}

where hash initially has a value of 0. It will only be calculated the first time the method is called.

As stated in the comments, using reflection breaks the immutability of the object.

like image 176
Sotirios Delimanolis Avatar answered Sep 22 '22 05:09

Sotirios Delimanolis