The Artima Developer Community
Sponsored Link

Java Answers Forum
toString() Proper use Please help!!!

2 replies on 1 page. Most recent reply: Apr 17, 2002 2:52 PM by Matt Gerrans

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 2 replies on 1 page
Jackie

Posts: 4
Nickname: jackie
Registered: Apr, 2002

toString() Proper use Please help!!! Posted: Apr 15, 2002 7:34 AM
Reply to this message Reply
Advertisement
Hi there,

Can anyone help me understand toString() functions? I kind of understand it but still a little confused. This is linked to my previous post on I/O file into a linkedlist. Well, the situation is that I have a class that defines the item within each nodes and the problem is that I don't quite know how to use the toString() function and I am not sure if my toString function in here is correct. I would appreciate any assistance!!!

//SAMPLE CODE
// Imported files
import java.io.*;
import java.util.Hashtable;
import java.lang.reflect.*;

class AttendeesInfo

/* The AttendeesInfo class stores all attendees
related info,
that is, the attendees's name, id number and address */

{
private String attendee; // stores attendees's name
private int idNumber; // stores attendees id number
private String address; // stores attendees address

AttendeesInfo ()
{
/* Method: AttendeesInfo
Description: This is constructor for AttendeesInfo class
Pre-condition:
Post-condition: Private variables are initialized */

attendee = " ";
idNumber = 0;
address = " ";

} // AttendeesInfo

AttendeesInfo (String conAttendee, int conId,String conAddress)
{
/* Method: AttendeesInfo
Description: This is copy constructor for AttendeesInfo class
Pre-condition: Copy constructor is called
Post-condition: Private variables are initialized with varibales sent
into the function */

attendee = conAttendee;
idNumber = conId;
address = conAddress;

} // AttendeesInfo

public String getAttendeeName ()
{
/* Method: getAttendeeName
Description: Returns the Attendee Name */

return attendee;

} // getAttendeeName

public int getID ()
{
/* Method: getID
Description: Returns ID */

return idNumber;

} // getID

public String getAddress ()
{
/* Method: getAddress
Description: Returns Address */

return address;

} // getAddress

public String toString()
{
/*Method: toString
Description:
Pre-condition:
Post-condition: */

java.util.Hashtable h = new java.util.Hashtable();
Class cls = getClass();
Field[] f= cls.getDeclaredFields();
try
{
AccessibleObject.setAccessible(f, true);
for(int i = 0; i< f.length; i++)
h.put(f.getName(), f.get(this));

}

catch (SecurityException e)
{

}

catch (IllegalAccessException e)
{

}

if(cls.getSuperclass().getSuperclass() != null)
h.put("super", super.toString());

return cls.getName() + h;

}

} // Attendee


Thomas SMETS

Posts: 307
Nickname: tsmets
Registered: Apr, 2002

Re: toString() Proper use Please help!!! Posted: Apr 17, 2002 7:05 AM
Reply to this message Reply
Jackie,
Don't make things too complex he...
Here under there is a sample code !
Please don't make a fool of your self, at least not in public :-) !

In an instance you can access all the attribute ! The certainly no need for reflexion (in the java sens at least).

Hope this helps.
For big Objects, you may be willing ot avoid String uneffectiveness by using StringBuffers !

In these XML days, a not so stupid idea is to have a pure text representation of the Object (the instance, he !!!) and an XML one. Entering the toString (), you may be willing to see what reprensentation you need to build !



package test.lang;
 
public class DemoToString
{
  DemoToString()
  {    
    System.out.println ("DemoToString - created");
  }
 
  
/** Method: toString
  * Description:
  * Pre-condition:
  * Post-condition: 
  */  
  public String toString()
  {
    // if (Representation.isXML)
    //   Build an XML reprensenting the Object
    // else
    //   Build an Simple Text reprensentaiton of the Object 
    //
    return "Hello;"
  }
  
/**  
  *
  */
  public static void main(String[] args)
  {
    DemoToString dts = new DemoToString ();    
    System.out.println ("Voila : " + dts);
  }
}  // create with www.jcreator.com



Thomas SMETS,
SCJP - Brussels

Matt Gerrans

Posts: 1153
Nickname: matt
Registered: Feb, 2002

Re: toString() Proper use Please help!!! Posted: Apr 17, 2002 2:52 PM
Reply to this message Reply
Let's stop making foo()s of ourselves and get back to basics by keeping things simple. toString() doesn't need to do anything fancy; the only requirement is that it returns a String. In your case, I would just do something simple like this:
public String toString()
{
   return "Attendee name: " + attendee +
          ", ID: " + idNumber +
          ", Address: " + address;
}

Depdending on your needs, you could separate the items by newlines (instead of commas), omit the labels ("Attendee name: ", etc.), omit any information that is not relevant (maybe you don't want the address included) or include additional information (for instance, perhaps you want to append super.toString()).

Also, if you wanted different kind of String representations of your class, you can write other methods, like toTabSeparatedString(), or whatever. toString() is just the default method that will be called when you do something like System.out.println( yourObjectInstance ); any other operation that wants to cast your object to a Sting.

Flat View: This topic has 2 replies on 1 page
Topic: file Previous Topic   Next Topic Topic: Need Help in Using LinkedList API implementation

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use