How does string class does caching of Hashcode in java

后端 未结 2 827
滥情空心
滥情空心 2021-01-17 06:24
Here what is written in String API for Hashcode------
public int hashCode() {
        int h = hash;
        if (h == 0 && value.length > 0) {
                     


        
相关标签:
2条回答
  • 2021-01-17 06:32

    Each string object has a field called "hash". whenever hashcode() is called on string object, a local variable int h is declared with initial value of "hash" field. As initially hash value will be zero, hash value of this string is computed and stored in hash field. Henceforth whenever hashcode() is called on this string "hash" field value will be returned because it will be non-zero value and therefore not enter the if condition.

    As String is immutable, hash value can be cached. If it is mutable, then this caching strategy will not work.

    As your creating the two Strings using new, both will be different instances, and therefore each will have their own hash fields.

    public final class String
    implements java.io.Serializable, Comparable<String>, CharSequence {
    /** The value is used for character storage. */
    private final char value[];
    
    /** Cache the hash code for the string */
    private int hash; // Default to 0
    ...
    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;
    }
    }
    
    0 讨论(0)
  • 2021-01-17 06:40

    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 Strings 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.

    0 讨论(0)
提交回复
热议问题