Home » Java Basics » 07 - A Simple GUI Application with Thread Management
7

The getColorString function

How the getColorString function works

String objects are immutable. Once a string object is created, it is never modified. New objects are created for every call to a String method or every use of the '+' operator. Many of these objects may hang around in memory and in rare cases, even slow things down. Such factors are immaterial in most cases because the memory allocated to temporary string variables is cleared either when the method completes execution or by Java's garbage collection mechanism. However, it is a good practice to use mutable StringBuffer Objects rather than String objects to perform String operations.

The getColorString method demonstrates the use of StringBuffer objects. The best design would include a method that returns such a list as a member method within the Fruit class itself. Our method, however, is in ShowFruits. We need a comma-separated list of colors that reflects the fruit's colors (these colors are held in an arraylist in the 'color' property). The method takes the ArrayList as input and returns a comma-separated String of colors. The colors are appended to a single StringBuffer Object. This object is converted to a string and the string is returned to the calling method.

Invocation:

getColorString(myFruits.get(currSlide).color)

getColorString:

private String getColorString(ArrayList color)  {
StringBuffer colorString = new StringBuffer();
ListIterator I = myFruits.get(currSlide).color.listIterator();
while (I.hasNext())
colorString.append(I.next()).append(", ");
colorString.delete(colorString.length()-2,colorString.length()-1 );
return colorString.toString();
}