我了解到使用 ==
而不是 String.equals()
来测试 String 相等性是来自魔鬼,因为每个 String 都是对其自身对象的引用.
但是如果我使用类似的东西
System.out.println("Hello" == "Hello");
它打印为真。
为什么?
最佳答案
事实并非如此。这仍然是一件坏事 - 您仍然会测试引用相等性而不是值相等性。
public class Test
{
public static void main(String[] args)
{
String x = "hello";
String y = new String(x);
System.out.println(x == y); // Prints false
}
}
如果您现在看到 == 测试“有效”,那是因为您确实拥有相同的引用。看到这种情况的最常见原因可能是字符串文字的驻留,但这在 Java 中一直存在:
public class Test
{
public static void main(String[] args)
{
String x = "hello";
String y = "hel" + "lo"; // Concatenated at compile-time
System.out.println(x == y); // Prints true
}
}
这是由 section 3.10.5 保证的Java 语言规范:
Each string literal is a reference (§4.3) to an instance (§4.3.1, §12.5) of class String (§4.3.3). String objects have a constant value. 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.
关于Java:为什么String相等性可以用==来证明?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1858569/