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

前端之家收集整理的这篇文章主要介绍了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对象的长度时,不会创建新对象.

原文链接:https://www.f2er.com/java/126017.html

猜你在找的Java相关文章