String class source code and its supplementary analysis

String class source code and its supplementary analysis

For details of String source code analysis, please refer to reprint: http://www.hollischuang.com/archives/99
Supplementary analysis:
1: About value
quote
       /**The value is used for character storage,---the first property inside String*/
        private final char value[ ];
        This is a character array, and it is a final type, he is used to store the string content, from fianl this From the keyword, we can see that once the content of String is initialized, it cannot be changed. Although there is such an example: String s = "a"; s = "b" However, this is not a modification of s, but a re-pointing to a new string. From here, we can also know that String actually uses char [] Implemented.

        String is final, which means that the class cannot be inherited, and the methods in String cannot be overridden. A char[ ] is maintained internally to store the String value.
public class IntertorTest {

    public static void main(String[] args) {
        // 1
        String str = "abc";
        // 2
        char[] data = {'a','b','c'};
        String a = new String(data);
    }
    
}
1 and 2 are actually the same.


2: About hash
 
quote
      /* Hash code of the cached string. Default is 0*/
        private int hash;

Question test site: Why is the hashCode value selected as 31? The detailed explanation is reproduced from: https://segmentfault.com/a/1190000010799123

First, look at the source code of hashCode() in the String class:
        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;
        }

The hashcode() method is interpreted as a mathematical expression, that is: h = 31^(n-1)*val[0]+31^(n-2)*val[1]+31^(n-3)*val [2]+...+31^0*val[n-1]
For example: String "abcd", h = 31^(3)*a + 31^(2)*b+31^( 1)*c+31^(0)*d

Answers to the problem:
1:31 is a prime number that is not too big or not, and is one of the preferred prime numbers as hashCode multipliers.
Note: Selecting the hash value as a prime number can reduce hash conflicts.
2: 31 can be optimized by the JVM, 31 * i = (i << 5) - i. (Optimization content: Multiplication can be replaced by shift and subtraction to obtain better performance.)

3: String class constant pool
        JVM performs some optimizations when instantiating string constants to improve performance and reduce memory overhead. Java is able to do this optimization because strings are immutable and can be shared without worrying about data conflicts.
        [String constant pool (String pool, String intern pool, String reserved pool)] is a special storage area in the Java heap memory. When a String object is created, the jvm will first go to the constant pool to find out whether the value exists. If the string value already exists in the constant pool, a new object will not be created, but an existing object will be referenced. If it does not exist in the constant pool, a new object will be created. (For String a = "1", a = "2")
Note: The object should not be created or re-referenced, all the changes are the address of the pointer.
Summary:
1: Use "" alone    
2: Objects created with new String("") will be stored in the heap and are newly created at runtime;    
3: Objects created by using a string concatenator that only contains constants such as "aa" + "aa" are also constants, compiled It can be determined during the period, and it has been determined to be stored in the String Pool;    
4: The object created by using the string concatenator containing variables, such as "aa" + s1, is only created during runtime and is stored in the heap;
quote
The statement String s = new String("abc") creates several objects.
Two objects are created:
the first object is the "abc" string stored in the constant pool, first if there is no constant pool, an object is created and stored in the constant pool. 
The second object is a String object in the JAVA heap, and the new objects exist in the heap (this will not change).

Question test site: Why is String designed to be final?
Answers to the problem:
1: For security.
        String is used by many Java classes (libraries) as parameters, such as network connection address URL, file path path, and String parameters required by the reflection mechanism, etc. If String is not fixed, it will cause various security risks. . And it is thread-safe in the case of multi-threading.
2: Support string constant pool, which can improve performance and reduce memory overhead.





Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326175547&siteId=291194637