What is the difference between Heap memory and string constant pool in java

后端 未结 1 2007
轻奢々
轻奢々 2021-01-26 02:25

In Java

  1. Object created using new operator will be stored in the heap memory.
  2. The object created using string lit
相关标签:
1条回答
  • 2021-01-26 02:47

    It is not correct to compare heap and constant pool. Especially using hashCode.

    Let's go step by step:

    1. Since Java 7 string pool is inside the heap memory. Read more.

    2. HashCode in Java is not related to memory address*

      JVM has an arg to specify hashCode default algorithm

      -XX:hashCode=k

      Number k could be one of:

      1. Park-Miller RNG
      2. foo(address, global state)
      3. 1 (const)
      4. incremental (++)
      5. address
      6. thread-local Xorshift (default in HotSpot, java 8)
    3. String override default hashCode implementation. It is based on string content. java.lang.String:

      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)
提交回复
热议问题