java - 为什么 String.intern() 在 Oracle JDK 1.7 中表现不同?

标签 java string

这是一个java代码片段:

public class TestIntern {
    public static void main(String[] argvs){
        String s1 = new StringBuilder("ja").append("va").toString();
        String s2 = new StringBuilder("go").append("lang").toString();
        System.out.println(s1 == s1.intern());
        System.out.println(s2 == s2.intern());
    }
}

并且根据不同的JDK表现不同

在 Oracle JDK 1.7 中输出是:

false
true

在 OpenJDK 1.6 中输出也是:

false
true

但在 Oracle JDK 1.6 中输出是:

false
false

正如此 String#intern 方法的 JavaDoc 所示

 * When the intern method is invoked, if the pool already contains a
 * string equal to this <code>String</code> object as determined by
 * the {@link #equals(Object)} method, then the string from the pool is
 * returned. Otherwise, this <code>String</code> object is added to the
 * pool and a reference to this <code>String</code> object is returned.
                           ~~~~
                             And what does *this* here mean? the string object
                             in the heap or in the string pool? if it returns 
                             object in the heap the out put should be:

                             true
                             true
                             otherwise should *always* be:

                             false
                             false
                             Am I right?

输出:

true
true

应该是预料之中的,但这三个 JDK 都没有产生。以及为什么 Oracle JDK1.6 给出:

false
false

结果呢?

我认为在 OracleJDK 1.7 和 openJDK 1.6 中,字符串池中必须有一些保留 字符串,它们是什么?是否有文档指定所有保留 字符串? 真的很困惑。

最佳答案

s1.intern() 是否返回 s1 或其他一些 String 对象取决于它在 interned 字符串池中找到的内容。如果池中已经有一些其他的 String 对象,intern() 将返回那个其他对象;否则它会将 s1 引用的 String 对象放入池中并返回该对象。

问题不在于不同的 Java 版本表现不同,而是在您运行测试时池恰好包含不同的东西。 Oracle JDK 1.7 和 openJDK 1.6 中的池碰巧已经包含字符串 "java" 而不是字符串 "golang" 我并不感到特别惊讶。

关于java - 为什么 String.intern() 在 Oracle JDK 1.7 中表现不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27812666/

相关文章:

java - 嵌套 for 循环中的 boolean 值

java - 在 Intellij IDEA 中设置 JMonkeyEngine

java - 需要 MVC 模式的帮助

python - 如何计算字符串中的方程式,python

android - 从字符串中删除空格

string - 最长公共(public)前缀属性

r - 如何在 gsub 模式中使用数字列表作为变量输入?

php - 如何在同一页面上将 Javascript 字符串传递给 php

java - javaFX 2.0 中的 Application.launch() 问题

java - Java 9 也适用于 WAR 文件吗?