代码之家  ›  专栏  ›  技术社区  ›  Zeemee

Java:为什么字符串相等可以用==?

  •  10
  • Zeemee  · 技术社区  · 16 年前

    == 而不是 String.equals()

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

    这是真的。

    为什么?

    3 回复  |  直到 16 年前
        1
  •  26
  •   Jon Skeet    16 年前

    没有。这仍然是一件不好的事情——您仍然需要测试引用相等,而不是值相等。

    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语言规范的定义:

    每个字符串文字都是一个引用 (§4.3)到实例(§4.3.1,§12.5) 对象具有常量值。一串 表达式(§15.28)-是“实习”的,因此 方法String.intern。

        2
  •  3
  •   Nick Fortescue    16 年前

    它没有改变。但是,Java编译器使用string.intern()确保源代码中的相同字符串编译为相同的字符串对象。但是,如果从文件或数据库加载字符串,它将不是同一个对象,除非使用String.intern()或其他方法强制加载。

    这是个坏主意,您仍然应该使用.equals()

        3
  •  1
  •   Aditya Singh    11 年前

    听着,这是个棘手的概念。

    这两者之间有区别:

    // These are String literals
    String a = "Hiabc";
    String b = "abc";
    String c = "abc";
    

    // These are String objects.
    String a = new String("Hiabc");
    String b = new String("abc");
    String c = new String("abc"); 
    

    如果字符串是对象,即。,

    String b = new String("abc");
    String c = new String("abc");
    

    b == c  
    

    会导致 false

    但是自从你 String b String c 是文字,

    b==c
    

    结果 true . 这是因为没有创建两个不同的对象。两者都有 a b 指向堆栈内存中的同一字符串。

    这就是区别。你是对的, == 比较内存位置。这就是原因,

    a.substring(2, 5) == b; // a,substring(2, 5) = "abc" which is at the location of b, and
    b == c // will be true, coz both b and c are literals. And their values are compared and not memory locations.
    

    为了使两个单独的字符串具有相同的值,但位于 String pool stack memory

    所以

    a.substring(2, 5) == b; // and
    b == c; // will be false. as not both are objects. Hence are stored on separate memory locations on the String pool.
    

    你必须使用

    a.substring(2, 5).equals(b);
    b.equals(c);