Pergunta

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?

Foi útil?

Solução

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);
}

Outras dicas

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!
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top