public class Child{
public static void main(String[] args){
String x = new String("ABC");
String y = x.toUpperCase();
System.out.println(x == y);
}
}
Output: true
So does toUpperCase()
总是创建一个新对象?
toUpperCase()
calls 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
}
....
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)