Java字符串实习,有什么保证?

hyd*_*yde 10 java string string-interning

问题归结为这段代码:

// setup
String str1 = "some string";
String str2 = new String(str1);
assert str1.equals(str2);
assert str1 != str2;
String str3 = str2.intern();

// question cases
boolean case1 = str1 == "some string";
boolean case2 = str1 == str3;
Run Code Online (Sandbox Code Playgroud)

Java标准是否对和的值有任何保证?当然,链接到Java规范的相关部分会很好.case1case2

是的,我查看了SO发现的所有"类似问题",发现没有重复,因为没有我发现这样回答了问题.不,这不是关于更换"优化"的字符串比较的误导想法equals==.

Per*_*ion 14

这是您的JLS报价,第3.10.5节:

每个字符串文字都是类String(第4.3.3节)的实例(第4.3.1节,第12.5节)的引用(第4.3节).String对象具有常量值.字符串文字 - 或者更一般地说,作为常量表达式(第15.28节)的值的字符串 - 是"实例化"以便使用String.intern方法共享唯一实例.

因此,测试程序由编译单元组成(第7.3节):

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"; }
Run Code Online (Sandbox Code Playgroud)

和编译单位:

package other;

public class Other { static String hello = "Hello"; }
Run Code Online (Sandbox Code Playgroud)

产生输出:true true true true false

这个例子说明了六点:

同一个包(第7节)中同一个类(第8节)中的文字字符串表示对同一个String对象的引用(第4.3.1节).

同一个包中不同类中的文字字符串表示对同一String对象的引用.

不同包中不同类中的文字字符串同样表示对同一String对象的引用.

由常量表达式计算的字符串(第15.28节)在编译时计算,然后将其视为文字.

在运行时通过串联计算的字符串是新创建的,因此是不同的.显式实现计算字符串的结果与具有相同内容的任何预先存在的文字字符串的字符串相同.

结合实习的JavaDoc,您有足够的信息来推断您的两个案例都将返回true.

  • @Alpedar - 实习生的实现依赖于原生和平台.我认为它是基于JavaDoc的线程安全,但他们不能保证(我已经找到)在官方文档支持这个. (2认同)

Evg*_*eev 5

我认为String.intern API提供了足够的信息

最初为空的字符串池由String类私有维护.

调用实习方法时,如果池已经包含等于此字符串对象的字符串(由equals(Object)方法确定),则返回池中的字符串.否则,将此String对象添加到池中,并返回对此String对象的引用.

因此,对于任何两个字符串s和t,当且仅当s.equals(t)为真时,s.intern()== t.intern()才为真.

所有文字字符串和字符串值常量表达式都是实体.字符串文字在The Java™Language Specification的3.10.5节中定义.