JDK中String类的intern方法实例

JDK的String类有一个intern方法:
public native String intern();

方法的注释:

/**
 * Returns a canonical representation for the string object.
 * <p>
 * A pool of strings, initially empty, is maintained privately by the
 * class {@code String}.
 * <p>
...
*/

该方法的作用是将字符串加载到常量池中,如果常量池中有数据,则直接取常量池中的数据,如果常量池中如果没有数据,则将数据写入常量池并返回常量池中的数据。
JDK6常量池位于方法区,JDK7以后常量池位于堆。

写3段代码测试下:

public static void test_intern_1() {
    String s1 = new String("123") + new String("123");
    s1.intern();
    String s2 = "123123";
    // true in JDK8
    System.out.println(s1 == s2);
}

在定义变量s2之前,调用s1.intern()方法将字符串123123复制到常量池,因此变量s1,s2指向相同引用。

public static void test_intern_2() {
    String s1 = new String("123") + new String("123");
    String s2 = "123123";
    s1.intern();
    // false in JDK8
    System.out.println(s1 == s2);
}

先定义定义变量s1s2,然后调用s1.intern()方法,但调用后未使用返回值,因此s1还是指向之前new String的引用。

public static void test_intern_3() {
    String s1 = new String("123") + new String("123");
    String s2 = "123123";
    s1 = s1.intern();
    // true in JDK8
    System.out.println(s1 == s2);
}

先定义定义变量s1s2,然后调用s1.intern()方法并且将返回值赋值给s1,由于s2已申明了字符串常量,
因此s1.intern()方法返回s2的引用,最终变量s1,s2指向相同引用。


参考:

posted @   cdfive  阅读(118)  评论(0编辑  收藏  举报
编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· Ollama——大语言模型本地部署的极速利器
· 使用C#创建一个MCP客户端
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示