假设我有一个类如下:
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/