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

前端之家收集整理的这篇文章主要介绍了Java字符串实习,有什么保证?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
该问题归结为以下代码
// 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;

Java标准是否对case1和case2的值提供任何保证?
当然,链接到Java规范的相关部分将是不错的.

是的,我看了所有的SO类似的问题,发现没有重复,因为我没有找到回答这个问题.不,这不是关于通过用==替换equals来“优化”字符串比较的错误的想法.

解决方法

这是你的JLS报价,Section 3.10.5

Each string literal is a reference (§4.3) to an instance (§4.3.1,
§12.5) of class String (§4.3.3). String objects have a constant value.
String literals-or,more generally,strings that are the values of
constant expressions (§15.28)-are “interned” so as to share unique
instances,using the method String.intern.

Thus,the test program consisting of the compilation unit (§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"; }

and the compilation unit:

package other;

public class Other { static String hello = "Hello"; }

produces the output: true true true true false true

This example illustrates six points:

Literal strings within the same class (§8) in the same package (§7)
represent references to the same String object (§4.3.1).

Literal strings within different classes in the same package represent
references to the same String object.

Literal strings within different classes in different packages
likewise represent references to the same String object.

Strings computed by constant expressions (§15.28) are computed at
compile time and then treated as if they were literals.

Strings computed by concatenation at run time are newly created and
therefore distinct. The result of explicitly interning a computed
string is the same string as any pre-existing literal string with the
same contents.

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

猜你在找的Java相关文章