JAVA
in Why
String
is a
Immutable
of the
?
1. Design : When creating a string (String str2 = "abc"), if it (originally a string str = "abc") already exists in the pool (in fact, the stack in memory), it will return a reference to the existing string, instead, How to create a new string and return the reference. If the string is not immutable, changing one of the references to a string will result in another reference to the wrong value.
2. efficiency : Allow string to cache its hashcode. The hashcode of string is used very frequently in Java. For example, in Hashmapzhong, a string designed to immutable ensures that hashcode is always the same, so hashcode can be cached without worrying about changes. In other words, it is more efficient to use hashcode every time you want to calculate it.
3. Security : String is widely used as a parameter by classes in Java, such as network connections, open files, and so on, if the string is not immutable, a connection or file changes will lead to serious security threats, one method thought is connected to a machine , and actually not. A mutable string will also cause a security problem with reflection because the parameters in the reflection are of type string.
Attached
String
,
StringBuffer
,
StringBuilder
comparison of the three in the speed of execution: StringBuilder > StringBuffer > String
String: Strings constant stringbuffer: String variable StringBuilder: string variable
As can be seen from the above name, string is a constant, and StringBuffer and StringBuilder are not the same, they are string variables, is a variable object, whenever we use them in the operation of the string, is actually operated on an object, This will not create a number of objects like string to operate, of course, the speed is fast. Again,StringBuilder is thread- insecure, and StringBuffer is thread-safe, so StringBuilder is the fastest.
5.4 String