本文介绍了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()
总是创建一个新对象吗?
So does toUpperCase()
always create a new object?
推荐答案
toUpperCase()
调用 toUpperCase(Locale.getDefault())
,这会创建一个新的 String
对象仅在必须时.如果输入的String
已经是大写,则返回输入的String
.
toUpperCase()
calls toUpperCase(Locale.getDefault())
, which creates a new String
object only if it has to. If the input String
is already in upper case, it returns the input String
.
不过,这似乎是一个实现细节.我在 Javadoc 中没有发现它.
This seems to be an implementation detail, though. I didn't find it mentioned in the 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
}
....
}
这篇关于toUpperCase() 方法什么时候创建一个新对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!