当前位置:网站首页>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 .
边栏推荐
- 事件监听机制
- Logstash excludes specific files or folders from collecting report log data
- Mihayou sued Minmetals trust, which was exposed to product thunderstorms
- 全面解析零知识证明:消解扩容难题 重新定义「隐私安全」
- Extract field year / quarter effect based on date
- LeetCode每日一练(两数之和)
- About MySQL: the phenomenon and background of the problem
- Deeply digitise, lead cloud nativity and serve more developers
- Regular matching starts with what, ends with what, starts with what, and ends with what
- The European unified charging specification act was passed before the end of the year, and it is planned to expand to products such as laptop and keyboard
猜你喜欢

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!

Raspberry pie preliminary use

Leetcode daily practice (Yanghui triangle)

Sliding window + monotone queue concept and example (p1886 Logu)

Simulated process scheduling

事件监听机制

# Cesium实现卫星在轨绕行
P. Simple application of a.r.a method in Siyuan (friendly testing)

数据中心表格报表实现定制统计加班请假汇总记录分享

Leetcode daily practice (sum of two numbers)
随机推荐
What is RPC
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!
When the publish / subscribe mode encounters NET
List to table
Kubernetes基础自学系列 | Ingress API讲解
Impressive questions
Nemo of pulseaudio (22)
localDateTime类型的时间(2019-11-19T15:16:17) 用oracle的时间范围查询
Yyds dry inventory brief chrome V8 engine garbage collection
Li Chuang EDA learning notes 16: array copy and array distribution
一个机器人位于一个 m x n 网格的左上角 。机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角。问总共有多少条不同的路径?【LeetCodeHot100】
Leetcode daily practice (longest substring without repeated characters)
Etcd visualization tool: kstone deployment (I), rapid deployment based on Helm
C language course design
Delete duplicate elements in the sorting linked list
Oracle concept II
Oracle概念三
Drawing for example study of flashcc
What do fast fashion brands care more about?
Special function calculator