gpt4 book ai didi

java - 字符串相等从字符数组构造字符串或连接字符

转载 作者:行者123 更新时间:2023-12-02 17:43:36 25 4
gpt4 key购买 nike

我理解方法内部:

String myStr1 = "good";
String myStr2 = "good";
System.out.println(myStr1==myStr2);

打印 true。出于同样的原因:

String myStr1 = "good";
String myStr2 = ""+'g'+'o'+'o'+'d';
System.out.println(myStr1==myStr2);

打印也是如此。

那为什么:

String myStr1 = "good";
char[] myCharArr = {'g', 'o', 'o', 'd' };
String myStr2 = ""+myCharArr[0]+myCharArr[1]+myCharArr[2]+myCharArr[3];
System.out.println(myStr1==myStr2);

打印错误?我没有看到最后两个代码之间的区别。任何想法?谢谢。

最佳答案

编译器会替换从常量表达式构建的多个值相等的字符串,如下所示:

String myStr1 = "good";
String myStr2 = ""+'g'+'o'+'o'+'d';
System.out.println(myStr1==myStr2);

具有从String.intern获取的唯一String对象。然后将该唯一的 String 对象分配给这两个变量。这就是为什么它们引用相等的原因。

String myStr1 = "good";
char[] myCharArr = {'g', 'o', 'o', 'd' };
String myStr2 = ""+myCharArr[0]+myCharArr[1]+myCharArr[2]+myCharArr[3];
System.out.println(myStr1==myStr2);

编译器无法优化它,因为它有一个不是常量表达式的数组引用。这会产生两个独立的 String 对象,它们的引用不相等。否则就会违反 Java 语言规范。

以下是 Java 语言规范中常量表达式的定义:

A constant expression is an expression denoting a value of primitive type or a String that does not complete abruptly and is composed using only the following:

  • Literals of primitive type and literals of type String (§3.10.1, §3.10.2, §3.10.3, §3.10.4, §3.10.5)

  • Casts to primitive types and casts to type String (§15.16)

  • The unary operators +, -, ~, and ! (but not ++ or --) (§15.15.3, §15.15.4, §15.15.5, §15.15.6)

  • The multiplicative operators *, /, and % (§15.17)

  • The additive operators + and - (§15.18)

  • The shift operators <<, >>, and >>> (§15.19)

  • The relational operators <, <=, >, and >= (but not instanceof) (§15.20)

  • The equality operators == and != (§15.21)

  • The bitwise and logical operators &, ^, and | (§15.22)

  • The conditional-and operator && and the conditional-or operator || (§15.23, §15.24)

  • The ternary conditional operator ? : (§15.25)

  • Parenthesized expressions (§15.8.5) whose contained expression is a constant expression.

  • Simple names (§6.5.6.1) that refer to constant variables (§4.12.4).

  • Qualified names (§6.5.6.2) of the form TypeName . Identifier that refer to constant variables (§4.12.4).

Constant expressions of type String are always "interned" so as to share unique instances, using the method String.intern.

A constant expression is always treated as FP-strict (§15.4), even if it occurs in a context where a non-constant expression would not be considered to be FP-strict.

来源:http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#d5e30892

关于java - 字符串相等从字符数组构造字符串或连接字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33987752/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com