我有一个关于在 java 语句中使用 new
的非常基本的问题。例如,最后的 return 子句使用 new
来表示 String
。为什么这里需要创建String
?在什么情况下人们会选择使用new
?
public class A extends java.lang.Object {
public int number;
public String toString() {
return new String("Value : " + number);
}
}
最佳答案
在任何情况下,由于 String
是不可变的,因此显式创建字符串副本是没有意义的,除非您确实需要来自 Javadoc 的关于 constructor 的副本。 :
Initializes a newly created String 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.
表达式"Value : "+ number
已计算为新的String
,因此返回 new String("Value : "+ number)
相当于
String tmp = "Value : " + number;
return new String(tmp);
您可以看到它创建了一个无用的副本。
关于java - Java 中字符串的 'new' 运算符有什么用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28576058/