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 :
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 .
String The reasons for immutability include Design considerations , Efficiency optimization , And security .