I’m planning to perform lots of deletes of the last character in StringBuilders. The solution to use
sb.setLength(sb.length() - 1); looks good to me. However, since these deletions will be in a loop, I need to know complexity of it.
The way I understand it is that this operation simply decrements some private attribute of my StringBuilder object and does not perform any copying/cloning/duplicating of the characters themselves, thus it is O(1) in time and should work fast.
Am I right?
From the documentation:
Sets the length of the character sequence. The sequence is changed to a new character sequence whose length is specified by the argument. For every nonnegative index k less than newLength, the character at index k in the new character sequence is the same as the character at index k in the old sequence if k is less than the length of the old character sequence; otherwise, it is the null character ‘u0000’. In other words, if the newLength argument is less than the current length, the length is changed to the specified length.
If the newLength argument is greater than or equal to the current length, sufficient null characters (‘u0000’) are appended so that length becomes the newLength argument.
The newLength argument must be greater than or equal to 0.
I would say yes. But I wouldn’t see it from the point of view of time complexity. The reason we use StringBuilder instead of String in a loop is because Strings are immutable. Hence a new string object will always be created when we try to change it. When you change the length of a StringBuilder object, no new object is created.