我只是想在 Sinkingpoint 的好答案旁边添加这个演示。
除非您知道每个字符串的来源,否则在字符串上使用是不安全==的,因为以某种方式构建的字符串(例如new String("A")Eli 的评论中的或.toString()此处使用的)不是相同的引用,即使两者确实使用相同的底层字符数组。
class Main
{
public static void main(String[] args)
{
String oneA = "A";
String twoA = "A";
String three = new StringBuilder().append('A').toString();
// We expect constant literals to be ==
System.out.print("A == A -> ");
System.out.println("A" == "A");
// Variables assigned the same literal are also ==
System.out.print("oneA == twoA -> ");
System.out.println(oneA == twoA);
// but a built-up String var is not == to the "literal" var.
System.out.print("oneA == three -> ");
System.out.println(oneA == three);
// If we intern() them they are again ==
System.out.print("oneA.intern() == three.intern() -> ");
System.out.println(oneA.intern() == three.intern());
// and of course, .equals() is always safe.
System.out.print("oneA .equals three -> ");
System.out.println(oneA.equals(three));
}
}
这个(在https://repl.it/languages/java上运行)的输出是:
A == A -> true
oneA == twoA -> true
oneA == three -> false
oneA.intern() == three.intern() -> true
oneA .equals three -> true
您可以安全地使用string1.equals(string2)或string1.intern() == string2.intern()