stay Java Lieutenant general String What is designed to be immutable is the result of comprehensive consideration of various factors , Want to understand this , Comprehensive memory required , synchronization , Data structure and security considerations .
In the following , I will make a summary for various reasons .

1. Need for string constant pool

String constant pool (String pool, String intern pool, String Reserved pool ) yes Java A special storage area in heap memory ,
When creating a String When object , If the string value already exists in the constant pool , A new object will not be created , It refers to existing objects .

As shown in the following code , Only one actual will be created in heap memory String object .
String s1="abc"; String s2="abc";

If the string object allows changes , It will lead to various logical errors , For example, changing one object will affect another independent object . Strictly speaking , The idea of constant pool , It's an optimization tool .

Think about it : If the code is as follows ,s1 and s2 It will also point to the same actual String Object ?
String s1="abc"; String s2="ab"+"c";
The answer is yes , Modern compilers will perform conventional optimizations , So they all point to the same object in the constant pool .

2. allow String Object cache HashCode
Java in String Object's hash code is frequently used , Like in hashMap In equal containers .

String invariance guarantees hash Uniqueness of codes , So you can cache with confidence . This is also a means of performance optimization , Which means you don't have to compute a new hash code every time . stay String The following code is included in the definition of the class :

3. Security

String By many Java class ( library ) Used as a parameter , for example Network connection address URL, File path path, And the reflection mechanism String Parameters, etc ,
If String Not fixed , All kinds of potential safety hazards will be caused .

4. summary

String The reasons for immutability include Design considerations , Efficiency optimization , And security . 


©2019-2020 Toolsou All rights reserved,
( Essence )2020 year 8 month 13 day C# Basic knowledge windform Realize two color sphere jmeter-while Summary of controller use The shortest path of maze BFS algorithm (python realization )el-select Get selected label value ( Essence )2020 year 7 month 13 day Wechat applet Inter communication page Centos7 lower mysql8.0 To install and change the initial password ;Vue Transfer parameters and receiving of page Jump Output string at specified position ( Detailed analysis )keras Data generator -- Data enhancement 11-5 Output string at specified position