Java - 构造函数中的自动字符串实习

Java - Automatic String interning within constructors

假设我有一个 class 如下:

class Apple {

    String apple;

    Apple(String apple) {
        this.apple = apple;
    }
}

为什么以下代码为真?

public boolean result() {
    Apple a = new Apple("apple");
    Apple b = new Apple("apple");

    return a.apple == b.apple;
}

Java 是否会在我的对象实例中自动实习字符串集?

唯一一次 Java 不实习字符串是在使用 new String("...") 创建时吗?

编辑:

感谢您的回答,这个问题的扩展就是

Apple a = new Apple(new String("apple"));
Apple b = new Apple(new String("apple"));

returns false同测

这是因为我将 String 的实例而不是 String 文字传递给构造函数。

Apple 中的字段 apple 是对 String.

引用

在您的情况下,该引用指的是一个驻留字符串,因为您已经使用将被驻留的字符串文字实例化了 Apple

并且由于 ab 是从相同的内部字符串创建的,因此 a.apple 指的是与 b.apple.

相同的字符串

确实 Java 如果您使用 new String.

则无法实习字符串

Does Java automatically intern Strings set within instances of my objects?

要点是:当您首先创建 Apple a 时,JVM 会提供包含 "apple"String 实例。 String 添加到 StringPool

因此,当您创建第二个 Apple b 时, 将重用 String,然后您在 a.appleb.apple 中具有相同的对象引用:

示例:

Apple a = new Apple("apple");
Apple b = new Apple(new String("apple"));

System.out.println(a.apple == b.apple);

输出:

false

Is the only time that Java doesn't intern Strings is when they're created using new String("...")?

如果您将 String 对象与 == 进行比较,您比较的是对象引用,而不是内容。

要比较 String 的内容,请使用 String::equals()String::intern()

示例

    // declaration
    String a = "a";
    String b = "a";
    String c = new String("a");

    // check references 
    System.out.println("AB>>" + (a == b));  // true, a & b references same memory position
    System.out.println("AC>>" + (a == c));  // false, a & c are different strings
    // as logic states if a == b && a != c then b != c.

    // using equals
    System.out.println("ACe>" + (a.equals(c))); // true, because compares content!!!!
     
    // using intern()
    System.out.println("ABi>" + (a.intern() == b.intern()));  // true
    System.out.println("BCi>" + (b.intern() == c.intern()));  // true

相关问题

  • What is the Java string pool and how is "s" different from new String("s")?
  • How do I compare strings in Java?