How does string class does caching of Hashcode in java

后端 未结 2 839
滥情空心
滥情空心 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: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.

提交回复
热议问题