Adverts

Time and again I have found the need to format a collection of object for display. Quite often this is for debugging but sometimes the text is seen by the end user. Generally there is a need to put a comma or some such other character between the individual items so that the resulting string is formatted nicely.

The problem is that a simple loop will add an extra comma at the end of the list of items that isn't needed. I have seen many solutions to this problem some of which are more elegant than others. The worst solutions usually require flags to detect the first or last item. Some check each time round the loop to see if they are processing the last item and a couple have just ignored the problem and hoped no one noticed. Checking each time round the loop is probably the best of the solutions just mentioned but I find the check inside the loop detracts from the readability of the loop. It also feels wasteful since you know at the outset of the loop that you are going to write a small number of extra characters at the end of the string. Therefore I present this solution which I have found to be very clean and reliable:

package example;

public class StringBufferTest {

 
/**
   *
@param args
   */
 
public static void main(String[] args) {
   
String[] letters = { "a", "b", "c" };
    StringBuffer buff =
new StringBuffer();
   
for( int i = 0, n = letters.length; i < n; i++ ) {
     
buff.append( letters[ i ] );
      buff.append
( ", " );
   
}
   
buff.delete( buff.length() - 2, buff.length() );
    System.out.println
( "Buffer: \"" + buff.toString() + "\"" );
 
}

}

This solution doesn't make any attempt to not write the last extra comma and space but just after exiting the loop it simply deletes the last two characters. Since you will be creating the string in a StringBuffer any way (or a StringBuilder if you are using 5.0 and using a single thread) the overhead of deleting a couple of characters is tiny and it keeps the code clean. This is far and away the cleanest solution I have found for this common little task.

Adverts

Donate and Help

Please support this site and
Bandwidth doesn't grow on trees y' know :o)

Adverts

Get Adsense