When does the toUpperCase() method create a new object?

后端 未结 1 1804
情深已故
情深已故 2021-02-19 20:11
public class Child{

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

        System.out.println(         


        
1条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-19 20:59

    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.

    This seems to be an implementation detail, though. I didn't find it mentioned in the Javadoc.

    Here's an implementation:

    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
        }
        ....
    }
    

    0 讨论(0)
提交回复
热议问题