toUpperCase()方法何时创建新对象?

Rah*_*Dev 12 java string object

public class Child{

    public static void main(String[] args){
        String x = new String("ABC");
        String y = x.toUpperCase();

        System.out.println(x == y);
    }
}
Run Code Online (Sandbox Code Playgroud)

输出: true

因此,没有toUpperCase()始终创建一个新的对象?

Era*_*ran 18

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
    }
    ....
}
Run Code Online (Sandbox Code Playgroud)

  • @Sarief如果它创建了一个新对象(并返回该新对象)`x == y`肯定会返回false. (4认同)
  • @Sarief它以某种方式得到[这个列表](https://stackexchange.com/questions?tab=hot),这往往会导致高流量. (2认同)
  • @ nits.kk这不应该适用于字符串的不可变对象 (2认同)