加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-14 14:47:54 所属栏目:Java 来源:网络整理
导读:我打算在StringBuilders中执行大量删除最后一个字符的操作.使用sb.setLength的解决方案(sb.length() – 1);在我看来很好.但是,由于这些删除将处于循环中,我需要知道它的复杂性. 我理解它的方式是这个操作简单地减少了我的StringBuilder对象的一些私有属性,并
我打算在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对象的长度时,不会创建新对象.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读