JVM - String Interning

栏目: Java · 发布时间: 7年前

内容简介:Java语言规定所有字符串字面量(string literals)和所有结果为字符串的常量表达式(string-valued constant expression)都被自动interned。或者也可以通过调用下面是一个例子来说明:

String interning (字符串拘留?),是一项把相同字符串值只保存一份copy的方法,比如 "abc""abc" 虽然是两个字符串,但是因为其值相同,所以只存留一份copy。String interning能够使得处理字符串的任务在时间上或空间上更有效率。不同字符串值保存在所谓 string intern pool 里。

Java语言规定所有字符串字面量(string literals)和所有结果为字符串的常量表达式(string-valued constant expression)都被自动interned。或者也可以通过调用 String#intern() 方法来手动interned。而interened字符串具有这个特性:当且仅当 a.equals(b)==true ,那么 a.intern() == b.intern()

下面是一个例子来说明:

package testPackage;
class Test {
    public static void main(String[] args) {
        String hello = "Hello", lo = "lo";
        System.out.print((hello == "Hello") + " ");
        System.out.print((Other.hello == hello) + " ");
        System.out.print((other.Other.hello == hello) + " ");
        System.out.print((hello == ("Hel"+"lo")) + " ");
        System.out.print((hello == ("Hel"+lo)) + " ");
        System.out.println(hello == ("Hel"+lo).intern());
    }
}
class Other { static String hello = "Hello"; }
package other;
public class Other { public static String hello = "Hello"; }

运行结果是:

true true true true false true
String
String
String

参考资料


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Python网络编程(第3版)

Python网络编程(第3版)

[美] Brandon Rhodes、[美] John Goerzen / 诸豪文 / 人民邮电出版社 / 2016-9 / 79.00元

本书针对想要深入理解使用Python来解决网络相关问题或是构建网络应用程序的技术人员,结合实例讲解了网络协议、网络数据及错误、电子邮件、服务器架构和HTTP及Web应用程序等经典话题。具体内容包括:全面介绍Python3中最新提供的SSL支持,异步I/O循环的编写,用Flask框架在Python代码中配置URL,跨站脚本以及跨站请求伪造攻击网站的原理及保护方法,等等。一起来看看 《Python网络编程(第3版)》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

html转js在线工具
html转js在线工具

html转js在线工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具