加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-14 16:17:22 所属栏目:Java 来源:网络整理
导读:该问题归结为以下代码: // setupString str1 = "some string";String str2 = new String(str1);assert str1.equals(str2);assert str1 != str2;String str3 = str2.intern();// question casesboolean case1 = str1 == "some string";boolean case2 = str1
该问题归结为以下代码:
// 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实习生,您有足够的信息来推断您的两个案例都将返回真实.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读