Java:为什么可以用==证明String等式? [英] Java: Why can String equality be proven with ==?

查看:121
本文介绍了Java:为什么可以用==证明String等式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解到它来自魔鬼用 == 来测试字符串相等而不是 String.equals(),因为每个String都是对它自己对象的引用。

I learned that it is from the devil to test String equality with == instead of String.equals(), because every String was a reference to its own object.

但是如果我使用的话是

System.out.println("Hello" == "Hello");

它打印为真。

为什么?

推荐答案

事实并非如此。这仍然是一件坏事 - 你仍然会测试引用相等而不是值相等。

It doesn't. It's still a bad thing to do - you'll still be testing reference equality instead of value equality.

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中:

If you're seeing == testing "work" now then it's because you genuinely have equal references. The most common reason for seeing this would probably be due to interning of String literals, but that's been in Java forever:

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
    }
}

这由第3.10.5节


每个字符串文字都是对实例的引用
(§4.3)(§4.3.1,§12.5)$ b类String的$ b(§4.3.3)。 String
对象具有常量值。字符串
文字 - 或者更一般地说,字符串
是常量
表达式(第15.28节)的值 - 是实习所以
用于共享唯一实例,使用
方法String.intern。

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等式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆