下面这两个陈述有什么区别?
String s = "text";
String s = new String("text");
最佳答案
new String("文本");
显式创建一个新的且引用不同的 String
对象实例; String s = "text";
可以重用字符串常量池中的实例(如果可用)。
您很少会想要使用new String(anotherString)
构造函数。来自 API:
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.
相关问题
- Java Strings: “String s = new String(”silly“);”
- Strings are objects in Java, so why don’t we use ‘new’ to create them?
参照区分的含义
检查以下代码片段:
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
但不是 ==
字符串,您可以使用 new String(anotherString)
构造函数。然而,需要再次指出的是,这是非常奇怪的,并且很少是意图。
引用文献
相关问题
关于java - "text"和新字符串 ("text"之间有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29218421/