In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-05 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/01 Report--
Why String in Java is immutable, this article introduces the corresponding analysis and solution in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible way.
Preface
String is a very basic and important class in the Java language, providing a variety of basic logic for constructing and managing strings. It is a typical Immutable class, declared as final class, and all properties are final (except for the hashCode method). Also because of its immutability, actions such as stitching and clipping strings will produce new String objects.
What is an immutable object
An immutable object is an object that can no longer be modified once created. That is to say, once an object is assigned, the reference or internal state of the object cannot be modified, and the public method exposed by the object does not allow you to modify
Second, why to use immutable objects
Using immutable objects has four advantages: caching, security, synchronization, and performance. Using immutable objects can save you a lot of unnecessary trouble, and you can only use immutable objects (such as caching results) in your scene. When passing parameters or assigning values to a mutable object, we must have the value of the copy variable, because we don't know when the value of the mutable object will be modified. But if you are using the final type, all you need is a reference to the variable copy. Because Java ensures that values of type final are not modified.
Third, the underlying data structure of immutable 1.String of String
String uses a character array value declared as final to store values, and once assigned, the address to which value points can no longer be modified. Although the value of the array can be modified, the String class itself does not provide a way to modify the value of the value array.
/ * The value is used for character storage. , /
Private final char value []
Add: when using final to modify the base type variable, the base type variable cannot be reassigned, so the base type variable cannot be changed; but for the reference type variable, JDK ensures that the address pointed to by the variable will not be changed (that is, it always points to the same object), and the value of the address (the value of the object) can be changed.
two。 String constant pool
In the previous article, it was pointed out that using immutable objects like String is easy to cache, and jdk provides string constant pools for String. Strings are the most commonly used data structure, and caching String and reusing it can greatly save Heap space because the same String variable points to the value of the same address in the constant pool. For example, the following code creates only one String object in the string constant pool
String string1 = "abcd"
String string2 = "abcd"
System.out.println (string1 = = string2)
/ / the output of the code is true
As shown in the figure, if the String is variable, then changing the content of the address pointed to by the string1 variable will cause the content of the string2 to be modified.
3. Safety
String is widely used to store sensitive information (username, password, URL, etc.) in Java applications, and it is also used by JVM Class Loader to load class information, so it is necessary to ensure the security of String.
Void criticalMethod (String userName) {
/ / 1. Security Check
If (! isAlphaNumeric (userName)) {
Throw new SecurityException ()
}
/ / 2. Update DB
Connection.executeUpdate ("UPDATE Customers SET Status = 'Active'" +
"WHERE UserName ='" + userName + "'")
}
As in the above code snippet, the method passes in a variable of userName. The first step is to check whether the changes are alphanumeric, and then execute sql to assume that String is variable, and when the method has already executed code 1 and has not executed code 2, the upstream caller also holds a reference to the parameter userName. If the caller modifies the value of userName at this time, it is tantamount to passing the security check of code 1. Then the risk of SQL injection will increase.
4. Synchronization
"immutable" ensures that in the concurrent programming model, different Thread cannot modify the value of String, and if a Thread modifies a string value, the value will be cached in StringPool, which means that the reference to String is safe.
5.Hashcode caching
JDK provides many data structures for hash operations: HashMap,HashTable,HashSet, etc., when operating on these classes, the hashCode () method is called frequently. "immutable" ensures that the value of the String object will not be modified, so the hash value will not be modified. The constant values can be cached so that when the hasCode () method is called later, the values in the cache can be directly fetched. The String code snippet in the JDK source code is as follows:
/ * * Cache the hash code for the string * /
Private int hash; / / Default to 0
/ * *
* Returns a hash code for this string. The hash code for a
* {@ code String} object is computed as
*
* s [0] * 31 ^ (nmur1) + s [1] * 31 ^ (nMur2) +. + s [n-1]
*
* using {@ code int} arithmetic, where {@ code s [I]} is the
* ith character of the string, {@ code n} is the length of
* the string, and {@ code ^} indicates exponentiation.
* (The hash value of the empty string is zero.)
*
* @ return a hash code value for this object.
, /
Public int hashCode () {
Int h = hash
If (h = = 0 & & value.length > 0) {
Char val [] = value
For (int I = 0; I < value.length; iTunes +) {
H = 31 * h + val [I]
}
Hash = h
}
Return h
}
You can see that the String object has a property hash that is used to cache the result of the first calculation of hasCode (), and then the hashCode () method is called to fetch it directly from the cache.
This is the answer to the question about why String is immutable in Java. I hope the above content can be of some help to you. If you still have a lot of doubts to be solved, you can follow the industry information channel to learn more about it.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.