The complexity of setLength is different from the operation (increase or decrease) the complexity of the increase operation is not O (1), I think it is O (n), because in this operation a new array will be generated, and each unused byte of the string editor with the replacement by '\ 0 'byte
But the reduction operation is O (1) complexity, because of which only the number of characters will be changed in this operation.
There is a source for the setLength method in the source file of the StringBuilder class
http://developer.classpath.org/doc/java/lang/StringBuilder-source.html
225: public void setLength(int newLength) 226: { 227: if (newLength < 0) 228: throw new StringIndexOutOfBoundsException(newLength); 229: 230: int valueLength = value.length; 231: 232: 234: ensureCapacity(newLength); 235: 236: if (newLength < valueLength) 237: { 238: 241: count = newLength; 242: } 243: else 244: { 245: 247: while (count < newLength) 248: value[count++] = '\0'; 249: } 250: }
source share