Possible Duplicate:
Difference Between Equals and ==
In JDK 1.6, can String equals operation can be replaced with ==?
How do I compare strings in Java?
在使用 Java-Strings 时,我没想到会出现以下结果:
public class Sandbox {
public static void main(String[] args) {
String a = "hello";
String b = "hello";
System.out.println(a == b); //true Why?, a and b both are seperate Objects
System.out.println(a == "hello"); //true Why?
System.out.println(a == new String(b)); //false As expected
}
}
我预计所有内容都是假的,因为“==”比较引用。为什么会出现这样的结果?
当我改变String b = "world"
, System.out.println(a == b);
返回false
。看起来好像正在比较 String-Object 的内容。
由于 Java 7 可以比较 switch-case-Statements 中的字符串,我认为它可能与 Java 版本有关。但正如描述的here ,当比较 Switch-Case 中的字符串时会调用 equals-Methode。
最佳答案
Java(从 1.0 版开始)始终保留字符串文字。这意味着常量字符串被添加到池中,并且重复项引用同一对象。
final String a = "hello";
final String b = "hell";
System.out.println(a == b + 'o');
这将打印 true
,因为编译器可以内联并简化表达式 b + 'o'
使其与“hello”相同。
关于java - 将两个 Java 字符串与 "=="进行比较时出现意外结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10122827/