"text" 和有什么不一样?和新的字符串(“文本")? [英] What is the difference between "text" and new String("text")?
问题描述
下面这两个语句有什么区别?
What is the difference between these two following statements?
String s = "text";
String s = new String("text");
推荐答案
new String("text");
显式地创建一个新的和引用不同的 String
对象实例;String s = "text";
可以重用 字符串常量池 中的一个实例(如果有的话).
new String("text");
explicitly creates a new and referentially distinct instance of a String
object; String s = "text";
may reuse an instance from the string constant pool if one is available.
您很少会想要使用 new String(anotherString)
构造函数.来自 API:
You very rarely would ever want to use the new String(anotherString)
constructor. From the API:
String(String original)
:初始化一个新创建的 String
对象,使其表示与参数相同的字符序列;换句话说,新创建的字符串是参数字符串的副本.除非需要原始的显式副本,否则不需要使用此构造函数,因为字符串是不可变的.
String(String original)
: Initializes a newly createdString
object so that it represents the same sequence of characters as the argument; in other words, the newly created string is a copy of the argument string. Unless an explicit copy of original is needed, use of this constructor is unnecessary since strings are immutable.
相关问题
String s1 = "foobar";
String s2 = "foobar";
System.out.println(s1 == s2); // true
s2 = new String("foobar");
System.out.println(s1 == s2); // false
System.out.println(s1.equals(s2)); // true
==
在两个引用类型上是一个引用标识比较.equals
的两个对象不一定是 ==
.在引用类型上使用 ==
通常是错误的;大多数情况下需要使用 equals
代替.
==
on two reference types is a reference identity comparison. Two objects that are equals
are not necessarily ==
. It is usually wrong to use ==
on reference types; most of the time equals
need to be used instead.
尽管如此,如果出于某种原因您需要创建两个 equals
而不是 ==
字符串,您可以使用 newString(anotherString)
构造函数.然而,需要再次说明的是,这是非常的,而且很少是本意.
Nonetheless, if for whatever reason you need to create two equals
but not ==
string, you can use the new String(anotherString)
constructor. It needs to be said again, however, that this is very peculiar, and is rarely the intention.
这篇关于"text" 和有什么不一样?和新的字符串(“文本")?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!