3

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?

1
  • 2
    String s = buf.toString(); and use s? Commented Mar 19, 2014 at 11:59

2 Answers 2

5

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);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Hmm... didn't know that. Thanks. (Are there more such elegant methods)?
@ambigram_maker, Yes, Check APIs.
2

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!
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.