Why String is immutable in Java ?--reference
String is an immutable class in Java. An immutable class is simply a class whose instances cannot be modified. All information in an instance is initialized when the instance is created and the information can not be modified. There are many advantages of immutable classes. This article summarizes whyString is designed to be immutable. A good answer depends on deep understanding of memory, synchronization, data structures, etc.
1. Requirement of String Pool
String pool (String intern pool) is a special storage area in Method Area. When a string is created and if the string already exists in the pool, the reference of the existing string will be returned, instead of creating a new object and returning its reference.
The following code will create only one string object in the heap.
String string1 = "abcd"; |
Here is how it looks:
If string is not immutable, changing the string with one reference will lead to the wrong value for the other references.
2. Caching Hashcode
The hashcode of string is frequently used in Java. For example, in a HashMap. Being immutable guarantees that hashcode will always the same, so that it can be cashed without worrying the changes.That means, there is no need to calculate hashcode every time it is used. This is more efficient.
In String class, it has the following code:
private int hash;//this is used to cache hash code. |
3. Facilitating the Use of Other Objects
To make this concrete, consider the following program:
HashSet<String> set = new HashSet<String>(); |
In this example, if String is mutable, it's value can be changed which would violate the design of set (set contains unduplicated elements). This example is designed for simplicity sake, in the real Stringclass there is no value field.
4. Security
String is widely used as parameter for many java classes, e.g. network connection, opening files, etc. Were String not immutable, a connection or file would be changed and lead to serious security threat. The method thought it was connecting to one machine, but was not. Mutable strings could cause security problem in Reflection too, as the parameters are strings.
Here is a code example:
boolean connect(string s){
|
5. Immutable objects are naturally thread-safe
Because immutable objects can not be changed, they can be shared among multiple threads freely. This eliminate the requirements of doing synchronization.
In summary, String is designed to be immutable for the sake of efficiency and security. This is also the reason why immutable classes are preferred in general.
reference from:http://www.programcreek.com/2013/04/why-string-is-immutable-in-java/
Why String is immutable in Java ?--reference的更多相关文章
- 为什么Java中的String是设计成不可变的?(Why String is immutable in java)
There are many reasons due to the string class has been made immutable in Java. These reasons in vie ...
- Why string is immutable in Java ?
This is an old yet still popular question. There are multiple reasons that String is designed to be ...
- Why String is Immutable or Final in Java
The string is Immutable in Java because String objects are cached in String pool. Since cached Strin ...
- JAVA —— String is immutable. What exactly is the meaning? [duplicate]
question: I wrote the following code on immutable Strings. public class ImmutableStrings { public st ...
- JAVA 中为什么String 是immutable的
本文翻译自:http://www.programcreek.com/2013/04/why-string-is-immutable-in-java/ 这是一个很老但很流行的问题,这里有几个原因Stri ...
- java Reference
相关讲解,参考: Java Reference 源码分析 Java Reference详解 Reference: // 名称说明下:Reference指代引用对象本身,Referent指代被引用对象 ...
- 为什么 String 是 immutable 类
二哥,你能给我说说为什么 String 是 immutable 类(不可变对象)吗?我想研究它,想知道为什么它就不可变了,这种强烈的愿望就像想研究浩瀚的星空一样.但无奈自身功力有限,始终觉得雾里看花终 ...
- Java Reference简要概述
@(Java)[Reference] Java Reference简要概述 Reference对象封装了其它对象的引用,可以和普通的对象一样操作. Java提供了四种不同类型的引用,引用级别从高到低分 ...
- 前台传参数时间类型不匹配:type 'java.lang.String' to required type 'java.util.Date' for property 'createDate'
springMVC action接收参数: org.springframework.validation.BindException: org.springframework.validation.B ...
随机推荐
- QVariant实质 (类似 C#中的装箱拆箱)
QVariant是一种可以存储不同类型的数据结构,在很多场合这是很有用得为了达到这种目的,可以想象,该对象应该存储对象的类型信息,数据信息以及其他辅助详细考虑用途,这种对象必须支持对不同对象的存储,对 ...
- 图片缩放时java.lang.IllegalArgumentException: pointerIndex out of range解决方案
版权声明:本文为博主原创文章,未经博主允许不得转载. 06-03 20:45:24.143: E/AndroidRuntime(1230): FATAL EXCEPTION: main06-03 20 ...
- 【Quick 3.3】资源脚本加密及热更新(三)热更新模块
[Quick 3.3]资源脚本加密及热更新(三)热更新模块 注:本文基于Quick-cocos2dx-3.3版本编写 一.介绍 lua相对于c++开发的优点之一是代码可以在运行的时候才加载,基于此我们 ...
- mysql select count(filed) 问题(where条件没有数据匹配的话也有数据返回)。
问题: SELECT count(*),user_id FROM tb_rp_logintrace WHERE id=-1 返回结果: count(*), user_id 0 ...
- Mapreduce-Partition分析
Partition所处的位置 Partition位置 Partition主要作用就是将map的结果发送到相应的reduce.这就对partition有两个要求: 1)均衡负载,尽量的将工作均匀的分配给 ...
- BZOJ_1180_[CROATIAN2009]_OTOCI_(LCT)
描述 http://www.lydsy.com/JudgeOnline/problem.php?id=1180 三种操作: 1.询问x,y是否连通,如果不连通,建一条边x,y 2.把x节点的权值改为t ...
- Master Nginx(4) - Nginx as a Reverse Proxy
Introduction to reverse proxying the proxy module legacy servers with cookies the upstream module ke ...
- InstallShield2008脚本安装制作方法Setup
//=========================================================================== // // File Name: S ...
- Android What is Application
本文转自:http://www.cnblogs.com/elleniou/archive/2012/05/16/2502661.html Application和Activity,Service一样是 ...
- NOIP2010关押罪犯 二分+二染色
这个题一上来 没有思路,后来想没有思路就二分吧 那么我们来二分 首先,大于当前的mid值的关系,不能出现在一个集合里 (即关系形成的图是一个二分图,判定二分图可以二染色) 如果不能形成二分图,那么说明 ...