【发布时间】:2012-04-12 11:40:53
【问题描述】:
可能重复:
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。
【问题讨论】:
-
请阅读this。
-
总而言之,一些字符串被interned(即缓存)并引用同一个对象,这就解释了为什么 == 可以工作。但是你不能依赖这种机制,应该使用 equals。
-
底线是,因为字符串仍然是对象,所以在绝大多数情况下,您应该使用
equals方法。