首先:"t" + "e"
是一个字符串文字,因为它会被编译器优化。此字符串文字也用于此行:
String a = new String("te");
现在,String(String)
构造函数制作了 String 的物理副本。所以,这意味着 a
和d
不是同一个对象。
然后:String.equals(String)
比较两个字符串。它表示内容是否相等而不是对象。这意味着您可能有两个不同的 String 对象,它们具有相同的字符序列,这将产生String.equals(String)
return true
。
String.intern()
将字符串放入字符串池中,如果它还没有的话。但是这种方法不能改变对象本身。所以这个代码示例将打印错误:
String literal = "lit";
String nonLiteral = "abclit".substring(3); // equals "lit"
nonLiteral.intern(); // "lit" was already in the String pool
// but `nonLiteral` is still `nonLiteral`
System.out.println(literal == nonLiteral); // false
但是,如果您这样做:它将返回 true:
String literal = "lit";
String nonLiteral = "abclit".substring(3); // equals "lit"
nonLiteral = nonLiteral.intern(); // "lit" was already in the String pool and
// it will return the object `literal`.
// Now the value is replaced.
System.out.println(literal == nonLiteral); // true