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

标签 java string string-interning

假设我有一个类如下:

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"));

使用相同的测试返回false

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

最佳答案

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

要点是:当您创建第一个 Apple a 时,JVM 会提供一个包含 “apple”String 实例。 字符串已添加到StringPool中。

因此,当您创建第二个 Apple b 时,重用String,然后您在 a.apple 中拥有相同的对象引用> 和 b.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

相关问题

关于Java - 构造函数中的自动字符串实习,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38325619/

相关文章:

java - MulticastSocket 加入/离开组、发送、接收线程安全

java - intern() 是否在池中创建了一个文字?

java - 为 RecyclerView 中的某些行禁用 ItemTouchHelper Swipe

java - Java 中的 FINAL 变量保存两个不同的值

java - 了解通配符约束 <? super T>

c - 在 C 中反转字符串不会输出反转的行

c++ - 如何在 Windows API 中指定与编码无关的字符串常量?

python - 拆分列表内的列表

Java、HashMaps 和使用字符串作为键 - 字符串值是否存储了两次?

java - 为什么虎书的符号表中要字符串intern?