Java 检查字符串是否相等
Java check equality for Strings
已编辑: 我在 java 中测试了这段代码,打印输出为 "true",而编译器比较引用而不是字符串的值为什么这是 "true"?
public class Main {
public static void main(String[] args) {
String s1 = "string";
String s2 = "string";
System.out.println(""+(s1==s2));
}
}
字符串相等规则在 Java 8 中没有改变,并且 s1==s2
在这种情况下总是打印 true
因为它们都指向常量池中的相同内存位置,这通常位于堆内存。
我刚和 Java6 核对了一下,是真的。
没有变化,== 运算符检查两个引用是否指向同一个对象。字符串文字放在字符串池中。所以 "string" 被放置在字符串池中,s1 和 s2 都指向它,因此输出为 true.
由编译器决定,在这种情况下,是否s1 == s2
。条件是测试 s1
和 s2
是否是同一个对象。这很可能是真的,因为一个明智的编译器会有一个常量池,但不一定如此。
但是,您的目的是比较字符串,而不是对象,因此 equals()
是正确的方法,使用 == 是不正确的。
在您编辑的问题中,您定义了两个字符串文字。根据 JLS § 3.10.5 这些文字是 interned:
a string literal always refers to the same instance of class String. This is because 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.
因此,对于 s1 == s2
,使用 ==
的引用相等性将始终 return true
,其中:
String s1 = "string";
String s2 = "string";
JLS 声明(几乎完全)与 Java 7 and Java 6
相同
请注意,某些 JDK 版本之间的字符串实习工作方式存在一些细微差别。参见,例如 "intern() behaving differently in Java 6 and Java 7"
已编辑: 我在 java 中测试了这段代码,打印输出为 "true",而编译器比较引用而不是字符串的值为什么这是 "true"?
public class Main {
public static void main(String[] args) {
String s1 = "string";
String s2 = "string";
System.out.println(""+(s1==s2));
}
}
字符串相等规则在 Java 8 中没有改变,并且 s1==s2
在这种情况下总是打印 true
因为它们都指向常量池中的相同内存位置,这通常位于堆内存。
我刚和 Java6 核对了一下,是真的。
没有变化,== 运算符检查两个引用是否指向同一个对象。字符串文字放在字符串池中。所以 "string" 被放置在字符串池中,s1 和 s2 都指向它,因此输出为 true.
由编译器决定,在这种情况下,是否s1 == s2
。条件是测试 s1
和 s2
是否是同一个对象。这很可能是真的,因为一个明智的编译器会有一个常量池,但不一定如此。
但是,您的目的是比较字符串,而不是对象,因此 equals()
是正确的方法,使用 == 是不正确的。
在您编辑的问题中,您定义了两个字符串文字。根据 JLS § 3.10.5 这些文字是 interned:
a string literal always refers to the same instance of class String. This is because 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.
因此,对于 s1 == s2
,使用 ==
的引用相等性将始终 return true
,其中:
String s1 = "string";
String s2 = "string";
JLS 声明(几乎完全)与 Java 7 and Java 6
相同请注意,某些 JDK 版本之间的字符串实习工作方式存在一些细微差别。参见,例如 "intern() behaving differently in Java 6 and Java 7"