public class Child{
public static void main(String[] args){
String x = new String("ABC");
String y = x.toUpperCase();
System.out.println(x == y);
}
}
输出:true
toUpperCase()
是否总是创建一个新对象?
public class Child{
public static void main(String[] args){
String x = new String("ABC");
String y = x.toUpperCase();
System.out.println(x == y);
}
}
输出:true
toUpperCase()
是否总是创建一个新对象?
toUpperCase()
方法调用toUpperCase(Locale.getDefault())
,只有在必要时才会创建一个新的String
对象。如果输入的String
已经是大写字母,它将返回输入的String
。
但是这似乎是一些具体实现的细节,我没有在Javadoc文档中找到相关提及。
下面是一个实现示例:
public String toUpperCase(Locale locale) {
if (locale == null) {
throw new NullPointerException();
}
int firstLower;
final int len = value.length;
/* Now check if there are any characters that need to be changed. */
scan: {
for (firstLower = 0 ; firstLower < len; ) {
int c = (int)value[firstLower];
int srcCount;
if ((c >= Character.MIN_HIGH_SURROGATE)
&& (c <= Character.MAX_HIGH_SURROGATE)) {
c = codePointAt(firstLower);
srcCount = Character.charCount(c);
} else {
srcCount = 1;
}
int upperCaseChar = Character.toUpperCaseEx(c);
if ((upperCaseChar == Character.ERROR)
|| (c != upperCaseChar)) {
break scan;
}
firstLower += srcCount;
}
return this; // <-- the original String is returned
}
....
}
x == y
肯定会返回 false。 - Erannew
创建了字符串,而没有调用 intern()
,因此正确地指出了实现方式是为什么在问题中提出的情况下没有创建新对象的原因。 - nits.kk