String class designed to final reason

String class designed to final reason

1, String Why designed to final

(1) To achieve the string pool

(2) for thread safety

(3) In order to achieve String can create HashCode immutability

2, design ideas

img

(1) Final modified String, String representing the non-inheritance of, final modified char [] represents the stored data can not change nature . But: Although the final represents the immutable, but merely referenced address is not changed, it does not mean that the array itself will not change, see the following picture.

img

(2) final is also possible to change the array itself, this time acting as well as private, it is because both ensure the immutability of String

3, designed as a final benefit

(1) because only when the strings are immutable, string pool be possible to achieve. Achieve string pool can save a lot of stack space at run time, because the same string different string variables are pointing to the pool. But if the string is variable, then the String interning will not be achieved, because in that case, if the variable changes its value, then the value of other points to the value of the variable will change together.

(2) String constant was designed as a class, which helps to share and improve performance . String object can be saved in a string constant pool for the same shared object literal string. If the String object is variable, so that it can not be shared, because the object value change once for a particular reference variable of type String, String will change the value of the shared object with the other variables of type String object referenced by the same time;

(3) Because strings are immutable, it is multi-thread safe , the same instance of a string can be shared by multiple threads. This will not be used because of security thread synchronization. String own is thread-safe.

(4) Because strings are immutable, so when it was created HashCode cached, do not need to be recalculated . This makes it suitable as a string of keys in the Map, the processing speed of the string to be faster than the other key objects. This is often the key in HashMap string.

4, if the harm is not designed to final

(1) If the string is variable, it can cause serious security problems . For example, database user name and password are in the form of a string passed to obtain connection to the database, or in the socket programming, the host name and port are passed as a string. Because strings are immutable, so its value can not be changed, otherwise hackers can drill loopholes, change the value of the object pointed to a string, resulting in vulnerabilities.

Published 19 original articles · won praise 11 · views 218

Guess you like

Origin blog.csdn.net/qqq3117004957/article/details/104517857