Java 检查 StringBuffer 是否为空

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39059514/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 20:51:10  来源:igfitidea点击:

Check if StringBuffer is empty

java

提问by Aman Shukla

Can anyone please tell me how I can use if-else condition with StringBuffer to check if it is empty?

谁能告诉我如何使用带有 StringBuffer 的 if-else 条件来检查它是否为空?

I am expecting something like this

我期待这样的事情

if (Stringbuffer is empty){ 
    // some condition 
}
else {
   // some other condition
}

回答by Andy Turner

StringBuffer.length():

StringBuffer.length()

[returns] the length of the sequence of characters currently represented by this object

[返回] 此对象当前表示的字符序列的长度

so you can use the fact that StringBuffer.length()returns zero (or not) to check if the buffer is empty (or not).

因此您可以使用StringBuffer.length()返回零(或不返回)的事实来检查缓冲区是否为空(或不为空)。



Note that you should probably be using StringBuilderinstead of StringBuffer. From the Javadoc of StringBuffer:

请注意,您可能应该使用StringBuilder而不是StringBuffer. 来自Javadoc 的StringBuffer

As of release JDK 5, this class has been supplemented with an equivalent class designed for use by a single thread, StringBuilder. The StringBuilderclass should generally be used in preference to this one, as it supports all of the same operations but it is faster, as it performs no synchronization.

从 JDK 5 版本开始,这个类已经补充了一个设计用于单线程的等效类,StringBuilder. 所述StringBuilder类通常应优先使用这一个,因为它支持所有相同的操作,但它是快的,因为它不执行同步。