Printing Lists

Example:

Convert a StringList object to a String of the form

( element-1 element-2 element-3 ....)

The following code could be used, where a StringBuffer is a standard class (in package java.lang) used to build a new String by appending strings or characters together:

class StringList
{
.... other stuff ....

 

public String toString()
{
StringBuffer b = new StringBuffer();
b.append("(");
StringList L = this;
b.append(first(L));
L = rest(L);
while( !isEmpty(L) )
  {
  b.append(" ");
  b.append(first(L));
  L = rest(L);
  }
b.append(")");
return b.toString();
}

 

Next Slide Previous Slide Contents