This is an extension of my previous question. When dealing with immutability, what is the best method for dealing with potential multiples. I'm working on "Times" and I want to avoid wasting resources as much as possible. Any general tips?
I will tread as far as possible from writing about specific Cattle Drive assignments. ----- First, if output is generated with the "print as you go" technique new objects aren't created. If for some reason text has to be concatenated take a look at the class StringBuffer, since it provides this functionality without creating a new object. I found the Str class in the JavaRanchCommon package interesting. It combines functionality of String and StringBuffer in a usable way. [ April 08, 2002: Message edited by: Michael Pearson ]
First, if output is generated with the "print as you go" technique new objects aren't created. If for some reason text has to be concatenated take a look at the class StringBuffer, since it provides this functionality without creating a new object.
Please elaborate. I don't quite understand what you mean here. New String objects are created every time you concatenate, but not with StringBuffer? And what technique is "print as you go" ?
Print as you go - instead of building a String by doing a bunch of concatenations, you simply call System.out.print() or println() in your method(s) where ever you need printing done.
Joined: Mar 11, 2001
Where is Marilyn? I'm not going to take credit for something she emphasized so well to me the past 12+ months. Print as you go just sends the String to output instead of returning it to the calling method. Why call a method and have it return a String to concatenate when you can print the String? Here's some pseudo code:
[ April 08, 2002: Message edited by: Michael Pearson ]
Strings are immutable. That means they cannot be changed. Every String is a new object. String + String creates 4 objects in the process of creating a new String object which is the result.
StringBuffer, on the other hand, is a mutable object. It can be changed. It does not create new objects in the process of changing.
In addition to Michael's example, remember that a statement like: System.out.println( text + moreText + moreAndMoreText ) ; can also be written as: System.out.print( text ); System.out.print( moreText ); System.out.println( moreAndMoreText );
Of course this can be carried to an extreme where readability is diminished.
Printing on the spot definitely beats accumulating and tracking Strings.
JavaBeginnersFaq "Yesterday is history, tomorrow is a mystery, and today is a gift; that's why they call it the present." Eleanor Roosevelt