当前位置:网站首页>Why is String immutable?
Why is String immutable?
2022-07-31 02:38:00 【likelong965】
String为什么不可变?
什么是不可变?
After an object is created,不能再改变它的状态,那么这个对象就是不可变的.
cannot change state
是指:不能改变对象内的成员变量,Include primitive data type values that cannot be changed,Reference data type reference cannot be changed,The state of the object pointed to by the reference cannot be changed either.
String为什么是不可变的?
这就要看jdk源码了,String源码如下:
public final class String
implements java.io.Serializable, Comparable<String>, CharSequence {
/** The value is used for character storage. */
private final char value[];
...
}
下面来解读一下,首先String类被final修饰,表明String类无法被继承,其次Stringunderlying core character arraychar value[]
也是由final修饰.final修饰的字段创建以后就不可改变.数组是引用数据类型,数组valueImmutable is just a simple reference address that cannot be changed,But the array object pointed to by the reference address is mutable.
Array variables are juststack上的一个引用,数组的本体结构在heap堆.String类里的value用final修饰,只是说stack里的这个叫value的引用地址不可变.It doesn't say that the data in the array itself is immutable.
如下代码示例:
final int[] value = {
1,2,3};
value[2] = 100; //这时候数组里已经是{1,2,100},And the code does not report errors
那么StringWhy on earth are immutable classes?
原因如下:
①String由finalModification prohibits inheritance,避免被其他人继承后破坏.②The character array is composed ofprivate和final共同修饰,finalThe decoration indicates that the array reference cannot be changed;privatemodifier indicates that character arrays can only be used inString类里使用,而且所有Stringmethod does not change the array elements.
因此String是不可变的关键都在底层的实现,而不是一个final了得.
为什么 String 被设计成不可变的?
1、String constant pool optimization required
The string constant pool is a special storage area for the method area.When a new string,if this string already exists in the constant pool,will return a reference to an existing string,而不是新建一个对象.
The following code will only create a single string object in the heap.
String string1 = "abcd";
String string2 = "abcd";
内存图是这样的:
如果String可变,then using a reference to change the value of the string will cause other references to point to the wrong value.
2、缓存哈希码
字符串的哈希码在 Java 中经常使用.例如,在 HashMap 或 HashSet 中.String immutability guarantees that the hash code is always the same,So you don't have to worry about changing the hash code during operation..This means there is no need to calculate every time the hash code is used.这样效率更高.这也是HashMap中的keyThe reason why strings are often used.
在 String 类中,它具有以下代码:
private int hash;//this is used to cache hash code.
3、Make other objects more convenient to use
为了使其具体化,请考虑以下程序:
HashSet<String> set = new HashSet<String>();
set.add(new String("a"));
set.add(new String("b"));
set.add(new String("c"));
for(String a: set)
a.value = "a";
在此示例中,如果 String 是可变的,you can change its value,这将违反 set 的设计(set 包含不重复的元素).当然,上面的例子只是为了演示,String类中并没有value属性.
4、出于安全考虑
like network addressesURL,文件路径pathAs well as user account passwords, etc. are usually stringString类型保存,如果字符串是可变的,will cause various security risks.
For example, using the passwordString类型保存,then it will stay in memory forever,until the garbage collector clears it.假如String类是可变的,then this password may be changed,导致出现安全问题.
5、线程安全
同一个字符串实例可以被多个线程共享,因为字符串不可变,本身就是线程安全的.
总之,String
出于效率和安全原因,它被设计为不可变的.
参考资料:
1、https://blog.csdn.net/weixin_38004638/article/details/115012897
2、https://www.programcreek.com/2013/04/why-string-is-immutable-in-java/
边栏推荐
猜你喜欢
【Android】Room —— SQLite的替代品
SQL注入 Less54(限制次数的SQL注入+union注入)
Force buckled brush the stairs (7/30)
What level of software testing does it take to get a 9K job?
Intranet Infiltration - Privilege Escalation
完整复制虚拟机原理(云计算)
The application of AI in the whole process of medical imaging equipment
Manchester City confuses fans with smart scarf that detects emotions
mmdetection trains a model related command
Pythagorean tuple od js
随机推荐
mycat的主从关系 垂直分库 水平分表 以及mycat分片联表查询的配置详解(mysql5.7系列)
General introduction to the Unity interface
力扣刷题之有效的正方形(每日一题7/29)
ShardingJDBC基本介绍
自动化办公案例:如何自动生成期数据?
coldfusion8 background scheduled tasks take shell
Introduction to flask series 】 【 flask - using SQLAlchemy
AI中的数学思想
How to do a startup CTO?
1. Non-type template parameters 2. Specialization of templates 3. Explanation of inheritance
Nacos
怎样做好一个创业公司CTO?
修改未正确放入沙盒造成苹果兼容性问题
基于opencv实现人脸检测
【C语言基础】解决C语言error: expected ‘;‘, ‘,‘ or ‘)‘ before ‘&‘ token
Coldfusion file read holes (CVE - 2010-2861)
YOLOV5学习笔记(三)——网络模块详解
Inter-vlan routing + static routing + NAT (PAT + static NAT) comprehensive experiment
mysql 索引
【CV项目调试】CUDNN_CONVOLUTION_FWD_SPECIFY_WORKSPACE_LIMIT问题