Supposing I have an ArrayList < String > named arr and a StringBuilder named buf, I use the following method to add the contents of buf to arr.

if ( !buf.toString( ).equals( "" ) ) {  //allow only non-empty Strings.
    arr.add( buf.toString( ) );
}

But it calls buf.toString( ) twice. I don't want that in my code. Moreover, is there any other (short or easy or efficient or something else) way to achieve this?

EDIT: Also, I do this in a loop, so is this efficient?

有帮助吗?

解决方案

There is API String#isEmpty() method to check empty Strings in Java, use it. It will be more elegant.

String temp = buf.toString();

if (!temp.isEmpty()) {
    arr.add(temp);
}

其他提示

I think you need a length() method instead of toString because is a call for super class method and create new instance of String so i recommend you a next :

if(buf.length()>0)
{
  arr.add(buf.toString()); // one call!
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top