java中固定长度的StringBuffer
在java中保持固定字符串缓冲区长度的最佳实践是什么?也就是说,如果固定值为10并且stringbuffer保存ABCDEFGHIJ,当我们附加K时,将导致A被清除,结果值将是BCDEFGHIJK。我正在考虑使用StringBuffer的reverse()和setLenght()方法组合,但不知道100 K 长度时其性能如何?
what is the best practise to hold a stringbuffer length fixed in java ? That is if the fixed value is 10 and stringbuffer holds ABCDEFGHIJ, when we append K that will cause A to be cleared and resulting value will be BCDEFGHIJK.I am thinking to use StringBuffer's reverse() and and setLenght() method combination but dont know how will its performance be for 100 K length.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
听起来您正在寻找一个循环缓冲区。您可以创建一个
char[]
并维护大小和逻辑开始。然后,当您需要将其转换为字符串时,只需创建两个字符串(一个从缓冲区末尾开始,一个从开头开始)并将它们连接在一起。不过,这将相对昂贵 - 尝试尽可能长时间地将其保留为循环缓冲区。确保在每个操作中您还考虑缓冲区未已满的可能性。操作示例:
It sounds like you're after a circular buffer. You could create a
char[]
and maintain a size as well as the logical start. Then when you need to convert it into a string, you can just create two strings (one from the end of the buffer and one from the start) and concatenate them together. That will be relatively expensive though - try to keep it just as the circular buffer for as much of the time as you can.Make sure that on each operation you also consider the possibility of the buffer not being full though. Sample operation:
您可以使用 删除:
更新:如果参数是长字符串,则会导致不必要的 StringBuffer 分配。为了避免这种情况,您可以首先缩短缓冲区,然后仅根据需要附加字符串中的字符:
You could use delete:
Update: If the parameter is a long string this results in unnecessary StringBuffer allocations. To avoid this, you could shorten the buffer first, and then append only as much characters of the string as needed: