Java:为什么String相等性可以用==来证明?

标签 java string

我了解到使用 == 而不是 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/

相关文章:

python - 使用空格分隔符连接多个 numpy 字符串数组

C# 版本的 SQL LIKE

php 仅当子字符串不属于另一个子字符串时才查找该子字符串

javascript - 如何将日期字符串标准化为 YYYY.MM.DD 格式?

java - 避免间接和冗余的方法调用

java - NetBeans 8.0.2 Java "Project Folder already exists and is not empty"

java - Hibernate 映射和唯一索引或主键违规

java - 如何读取 tagx/jspx 中的系统属性?

java - 如何获取员工 ID 并将其放入其他元素中

java - 如何计算基于结构的字符串相似度?