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 ...
随机推荐
- QT4项目升级到QT5遇到的问题和解决方法
QT4升级到QT5改动: PC部分: [改QTDIR变量] 在工程根目录下找到.user文件, 如InnoTabPlugin.vcxproj.user 修改指向你的QT5根目录: <Proper ...
- 163. Missing Ranges
题目: Given a sorted integer array where the range of elements are [lower, upper] inclusive, return it ...
- 132. Palindrome Partitioning II
题目: Given a string s, partition s such that every substring of the partition is a palindrome. Return ...
- RxJava开发精要3-向响应式世界问好
原文出自<RxJava Essentials> 原文作者 : Ivan Morgillo 译文出自 : 开发技术前线 www.devtf.cn 转载声明: 本译文已授权开发者头条享有独家转 ...
- 【HDOJ】4267 A Simple Problem with Integers
树状数组.Easy. /* 4267 */ #include <iostream> #include <string> #include <map> #includ ...
- Java之sleep和wait的区别
这个问题在面试线程方面的知识时,基本上属于必问的问题.因此这里有必要做一个较为详细的总结. 区别一 首先需要明白的是这两个方法根本来自不同的类,sleep来自Thread,wait来自Object类. ...
- Sublime Text主题下载、安装与配置
从下面地址下载主题包,以下载第一个为例,解压缩并重命名为Theme – Flatland 备注:下载好的文件中 .sublime-theme后缀的表示界面主题(theme),.tmTheme表示颜色 ...
- WIKIOI 1222信与信封问题
题目描述 Description John先生晚上写了n封信,并相应地写了n个信封将信装好,准备寄出.但是,第二天John的儿子Small John将这n封信都拿出了信封.不幸的是,Small Joh ...
- 理解SVG坐标系统和变换: 建立新视窗
在SVG绘制的任何一个时刻,你可以通过嵌套<svg>或者使用例如<symbol>的元素来建立新的viewport和用户坐标系.在这篇文章中,我们将看一下我们如何这样做,以及这样 ...
- 使用 jQuery 进行前端验证 -- 1
如今很多的网站偶会有不同层次的验证去验证用户输入的信息是否符合我们所需要的数据类型.并且可以说任何有输入的地方都需要的去验证,验证一方面是要求用户输入正确格式的数据,同时也是避免恶意的用户进行非法的输 ...