当前位置:网站首页>Why should string be designed to be immutable?
Why should string be designed to be immutable?
2022-06-27 16:57:00 【Iron helmet and anchor】
interpreter : Anchor
Translation date : 2013 year 11 month 18 Japan
Link to the original text : Why string is immutable in Java ?
It's a platitude (This is an old yet still popular question). stay Java Lieutenant general String Designed to be immutable is the result of taking into account various factors , To understand this question , Need integrated memory , Sync , Data structure and security considerations . In the following , I will make a summary for various reasons .
1. The need for string constant pool
String constant pool (String pool, String intern pool, String Keep the pool ) yes Java A special storage area in heap memory , When creating a String Object time , If the string value already exists in the constant pool , A new object will not be created , It's a reference to an existing object .
This is shown in the following code , Only one actual... Will be created in heap memory String object .
String s1 = "abcd";
String s2 = "abcd";
- 1.
- 2.
The schematic diagram is shown below :

chart 1
If the string object is allowed to change , Then it will lead to all kinds of logical errors , For example, changing one object can affect another independent object . Strictly speaking , This idea of constant pool , It's a means of optimization .
please reflection : Suppose the code looks like this ,s1 and s2 It will also point to the same actual String Objects? ?
String s1= "ab" + "cd";
String s2= "abc" + "d";
- 1.
- 2.
Maybe this question goes against the novice's intuition , But considering that modern compilers do regular optimizations , So they all point to the same object in the constant pool . perhaps , You can use it.
jd-gui Look at the compiled class file .
2. allow String Object caching HashCode
Java in String The hash code of the object is frequently used , For example hashMap In a container .
String invariance guarantees hash Uniqueness of codes , So it's safe to cache . It's also a performance optimization tool , That means you don't have to compute a new hash code every time . stay String Class definition has the following code :
private int hash;// Used to cache HashCode
- 1.
3. Security
String By many Java class ( library ) Used as a parameter , for example Network connection address URL, File path path, And what reflection mechanisms need String Parameters, etc. , If String It's not fixed , Will cause all kinds of security risks .
Suppose you have the following code :
boolean connect(string s){
if (!isSecure(s)) {
throw new SecurityException();
}
// If it can be modified elsewhere String, Then there will be all kinds of unexpected problems / error
causeProblem(s);
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
On the whole , String The reasons for immutability include Design considerations , Efficiency optimization problem , And security . in fact , This is also Java Many of the interviews " Why? " The answer .
边栏推荐
- [pyGame games] this "eat everything" game is really wonderful? Eat them all? (with source code for free)
- tensorflow求解泊松方程
- IDE Eval reset unlimited trial reset
- QT5 之信号与槽机制(信号与槽的基本介绍)
- The time of localdatetime type (2019-11-19t15:16:17) is queried with the time range of Oracle
- About MySQL: the phenomenon and background of the problem
- Annual comprehensive analysis of China's audio market in 2022
- Raspberry pie preliminary use
- Oracle concept II
- Qt5 signal and slot mechanism (demonstrate the correlation between the control's own signal and slot function)
猜你喜欢

【牛客刷题】NowCoder号称自己已经记住了1-100000之间所有的斐波那契数。 为了考验他,我们随便出一个数n,让他说出第n个斐波那契数。如果第n个斐波那契大于6位则只取后6位。

Simulated process scheduling

Kubernetes basic self-study series | introduction to ingress API

d3dx9_ How to repair 32.dll? d3dx9_ Solution to 32.dll missing

How to improve it electronic equipment performance management
#yyds干货盘点#简述chromeV8引擎垃圾回收

Oracle概念二

Cesium realizes satellite orbit detour

继手机之后 报道称三星也削减了电视等家电产品线的产量

Autodesk NavisWorks 2022 software installation package download and installation tutorial
随机推荐
Handling method of occasional error reporting on overseas equipment
2022年中国音频市场年度综合分析
Hung - Mung! HDD Hangzhou station · salon hors ligne vous invite à construire l'écologie
阿里云刘珅孜:云游戏带来的启发——端上创新
LeetCode 124. Binary tree maximum path sum - binary tree series question 8
# Cesium实现卫星在轨绕行
QT5 之信号与槽机制(演示控件自带的信号与槽函数关联)
Sliding window + monotone queue concept and example (p1886 Logu)
Nemo of pulseaudio (22)
Related configuration commands of Huawei LACP
The interview lasted for half a year. Last month, I successfully got Alibaba p7offer. It was all because I chewed the latest interview questions in 2020!
Oracle概念三
What do fast fashion brands care more about?
C语言集合运算
Raspberry pie preliminary use
Alibaba cloud liupeizi: Inspiration from cloud games - innovation on the end
Oracle concept II
The two trump brand products of Langjiu are resonating in Chengdu, continuously driving the consumption wave of bottled liquor
特殊函数计算器
Simulated process scheduling