JVM - String Interning

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

内容简介: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

参考资料


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

查看所有标签

猜你喜欢:

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

PHP and MySQL Web Development

PHP and MySQL Web Development

Luke Welling、Laura Thomson / Sams / July 25, 2007 / $49.99

Book Description PHP and MySQL Web Development teaches you to develop dynamic, secure, commerical Web sites. Using the same accessible, popular teaching style of the three previous editions, this b......一起来看看 《PHP and MySQL Web Development》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器