Tuesday, October 26, 2010

Revised Reverse

The reverse() method reverses the order of the characters in a StringBuffer object. Unlike the methods of immutable objects, this method changes the data of its object. For practice, let us write another method that does this.
The append() method puts a new character at the end of a StringBuffer object. No new object is created. We can use this method to build up the reversed characters as the original String is scanned from right to left:
public class ReverseTester
{

  public static String reverse( String data )
  {
    StringBuffer temp = new StringBuffer();

    for ( int j=data.length()-1; j >= 0; j-- )  // scan the String from right to left
      temp.append( data.charAt(j) );            // append characters on the right

    return temp.toString();      // return a String created from the StringBuffer
  }

  public static void main ( String[] args )
  {
    System.out.println( reverse( "Hello" ) );
  }
}
In this version of reverse(), only two new objects are created: the StringBuffer and the String object that is returned to the caller.

Note that program does not make any assumptions about the size of the original String

No comments:

Post a Comment

Chitika