Thought this was cool.

3 views
Skip to first unread message

Jordan Hourani

unread,
Feb 18, 2012, 7:12:02 AM2/18/12
to cs310_s12
Found this code online @ http://www.javapractices.com/topic/TopicAction.do?Id=55

Using a StringBuilder to implement a toString() method = Pure
Awesomeness!!

@Override public String toString() {
StringBuilder result = new StringBuilder();
String NEW_LINE = System.getProperty("line.separator");

result.append(this.getClass().getName() + " Object {" + NEW_LINE);
result.append(" Name: " + fName + NEW_LINE);
result.append(" Number of doors: " + fNumDoors + NEW_LINE);
result.append(" Year manufactured: " + fYearManufactured +
NEW_LINE );
result.append(" Color: " + fColor + NEW_LINE);
//Note that Collections and Maps also override toString
result.append(" Options: " + fOptions + NEW_LINE);
result.append("}");

return result.toString();
}

Output would be :
-----------------------------------------------------
Truck Object {
Name: Dodge
Number of doors: 2
Year manufactured: Wed Aug 29 15:49:10 ADT 2007
Color: Fuchsia
Options: [Air Conditioning]
}
Reply all
Reply to author
Forward
0 new messages