Java StringBuilder.setLength() – 是时间复杂度O(1)?

我打算在StringBuilders中执行大量删除最后一个字符的操作.使用sb.setLength的解决方案(sb.length() – 1);在我看来很好.但是,由于这些删除将处于循环中,我需要知道它的复杂性.

我理解它的方式是这个操作简单地减少了我的StringBuilder对象的一些私有属性,并且不对字符本身执行任何复制/克隆/复制,因此它是O(1)及时并且应该快速工作.

我对吗?

解决方法

从文档:

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.

我会说是的.但是从时间复杂性的角度来看,我不会看到它.我们在循环中使用StringBuilder而不是String的原因是因为字符串是不可变的.因此,当我们尝试更改它时,将始终创建一个新的字符串对象.更改StringBuilder对象的长度时,不会创建新对象.

dawei

【声明】:唐山站长网内容转载自互联网,其相关言论仅代表作者个人观点绝非权威,不代表本站立场。如您发现内容存在版权问题,请提交相关链接至邮箱:bqsm@foxmail.com,我们将及时予以处理。