Confusion with toString() method

hi...can you please tell me how to use the toString() method? i'm trying to print out a Vector and convert whatever is in it to strings but the memory addresses keep appearing. i tried using the method to convert (ie. getNames.toString, where getNames returns a vector, but it doesnt seem to work. i dont know what the problem is. i would really appreciate your help...

The objects in the Vector (or whatever collection
type you use) need to implement their owntoString()
method. Otherwise they just inherit
java.lang.Object's implementation, which gives you
the result you are seeing -- how should the system
magically know what to show for a string
representation of any willy-nilly object?Furthermore: the OP actually needs to call it on the
Vector's elements, not on the Vector itself.Not necessarily. I believe Vector.toString() iterates over the elements in it, invoking toString() on them.

Similar Messages

  • Having some problems with toString method.

    Hi well my toString method is fine but what I don't understand is why am I getting the ouput for the toString where I am not supposed to.
    import java.text.DecimalFormat;
        public class Sphere
       //Variable Declarations.
          private int diameter;
          private double radius;
       //Constructor: Accepts and initialize instance data.
           public Sphere(int sp_diameter)
             diameter = sp_diameter;     
             radius =(double)diameter/2.0;
       //Set methods: Diameter
           public void setDiameter(int new_diameter)
             diameter = new_diameter;
             radius = (double) diameter/2.0;
       //Get methods: Diameter
           public int getDiameter()
             return diameter;
       //Compute volume and surface area of the sphere
           public double getVolume()
             return  4 * Math.PI * radius * radius * radius / 3;
           public double getArea()
             return  4 * Math.PI * radius * radius;
       //toString method will return one line description of the sphere
           public String toString()     
             DecimalFormat fmt1=new DecimalFormat("0.###");
             String result = "Diameter : " + fmt1.format(diameter)+ "\tVolume: " + fmt1.format(getVolume()) + "\tArea: " +fmt1.format(getArea());
             return result; // This is fine .. the problem is the driver
    Driver
           public static void main(String[]args)
             Sphere sphere1, sphere2, sphere3;
             sphere1 = new Sphere(10);
             sphere2 = new Sphere(12);
             sphere3 = new Sphere(20);
             System.out.println("The sphere diameter are: "); //Here is the problem  for the output I only want the diameter, but I am getting the toString output here too..
             System.out.println("\tFirst Sphere diameter is: " + sphere1);
             System.out.println("\tSecond Sphere diameter is: "+ sphere2);
             System.out.println("\tThird Sphere diameter is: " + sphere3);
          //Prints the Sphere Volume and  Surface Area.
             DecimalFormat fmt = new DecimalFormat("0.###");
             System.out.println("\nTheir Volume and Surface Area: ");
             System.out.println("\tSphere1: " + "Volume: " + fmt.format(sphere1.getVolume()) + "\tSurface Area: " + fmt.format(sphere1.getArea()));
             System.out.println("\tSphere2: " + "Volume: " + fmt.format(sphere2.getVolume()) + "\tSurface Area: " + fmt.format(sphere2.getArea()));
             System.out.println("\tSphere3: " + "Volume: " + fmt.format(sphere3.getVolume()) + "\tSurface Area: " + fmt.format(sphere3.getArea()));
          //Change the diameter of the sphere.
             sphere1.setDiameter(11);
             sphere2.setDiameter(15);
             sphere3.setDiameter(25);
             System.out.println("\nNew diameter is: ");
             System.out.println("\tFirst Sphere diameter is: " + sphere1);
             System.out.println("\tSecond Sphere diameter is: " + sphere2);
             System.out.println("\tThird Sphere diameter is: " + sphere3);
          //Prints the Sphere Volume and  Surface Area.
             System.out.println("\nTheir Volume and Surface Area: ");
             System.out.println("\tSphere1: " + "Volume: " + fmt.format(sphere1.getVolume()) + "\t\tSurface Area: " + fmt.format(sphere1.getArea()));
             System.out.println("\tSphere2: " + "Volume: " + fmt.format(sphere2.getVolume()) + "\tSurface Area: " + fmt.format(sphere2.getArea()));
             System.out.println("\tSphere3: " + "Volume: " + fmt.format(sphere3.getVolume()) + "\tSurface Area: " + fmt.format(sphere3.getArea()));
          //Using the toString Method.
             System.out.println("\nFirst sphere: " + sphere1);
             System.out.println("\nSecond sphere: " + sphere2);
             System.out.println("\nThird sphere: " + sphere3);
     

    System.out.println("The sphere diameter are: "); //Here is the problem for the output I only want the diameter, but I am getting the toString output here too..
    System.out.println("\tFirst Sphere diameter is: " + sphere1);
    System.out.println("\tSecond Sphere diameter is: "+ sphere2);
    System.out.println("\tThird Sphere diameter is: " + sphere3);
    If you only want the Diameter, than use a formatter and get the diameter like you did when you printed the surface area and volume. Or, print shpere1.getDiameter();
    You have already demonstrated the solution to your problem elsewhere in your code, I think you need to re-read and understand what you have done so far.

  • Plz help.... toString() method

    hi....i came accross this sample of toString method. I was wondering how do i return all the variables instead of dont concat ?Pleas help...
    class ToStringClass {
    String firstName;
    String lastName;
    public ToStringClass(String fname, String lname) {
    this.firstName = fname;
    this.lastName = lname;
    // Override the toString() method
    public String toString() {
    return lastName + ", " + firstName;
    }

    sorry for the misleading question... here is the simple full coding of it
    public class ToStringObjectExample {
        public static void main(String[] args) {
               // Overriding the equals() method
            ToStringClass tsc2 = new ToStringClass("Jane", "Doe");
            System.out.println("Class with toString() method    : " + tsc2);
    class ToStringClass {
        String firstName;
        String lastName;
        public ToStringClass(String fname, String lname) {
            this.firstName = fname;
            this.lastName = lname;
        // Override the toString() method
        public String toString() {
            return lastName + ", " + firstName;
    }the output will be display like :-
    Class with toString() method    : Doe, JaneI was thinking how do i display or print the output directly like below :-
    Doe
    Jane
    , which means that displaying the value of each variable. how do i do the return statement?

  • Confused with JList...

    Ok... I'm working on a section of code for my GUI app that requires a JList (or something comparable).
    I've read the tutorials and API, and I'm getting confused on how to do what I want. From what I gather, I need to use a ListModel and a listener, but putting it all together is the problem.
    Here is what I am trying to accomplish:
    I'm writing an RMI group chat app. It's came together wonderfully so far (I just have GUI issues and a couple features to add). I need a user list with the users currently online. Since the users online with vary often, the list needs to be changed dynamically. There's more... The users are divided by department, and the department has a colored heading in the list, the users for that department are underneath it.
    Here's how I am handling the data:
    When a user joins or exits, the server fires a remote call to each client to update the userlist. It passes the departments and users as a hashtable. I then loop through each department (setting the department to the list with a colored cell). While each department is looped through, it loops through the users hash to see if they are in that department. If they are, it adds that username to the list. Obviously, since the list will be updated continuouly, the list must be cleared before it is repopulated. Finally, when any user is clicked on, it invokes a method (the method is arbituary at this point).
    I know this is a lot of code, but I'm confused on how to even begin this section of my app. If anyone has a solution or can point me in the right direction, that would wonderful.
    Thanks so much!
    Jason

    Well, you could just clear all and loop thru and create a Vector or Object[] and call setListData() on the list, which will update. However, this is not the best approach because of all the processing of the list for each change.
    What I would do is first create a class extending AbstractListModel which can hold all your list items. So you need an add method and remove method, and a list to store the objects in, like ArrayList. If possible, just add or remove whatever was actually added or removed, don't update the whole list. The getElementAt method can just call the get method on the internal list.
    Then create an object that implements comparable that contains the user name and the department they are in. The compareTo method can check the departments and if they are equal, compare the names to sort, otherwise compare the department strings. This will allow the objects to be sorted in the list easily. Make sure to implement equals in the object as well.
    For add, after adding to the internal list, sort it with Collection.sort(), find the index of the item just added and call fireIntervalAdded(this, index, index) from the AbstractListModel. For remove, get the current index, then remove the item and call fireIntervalRemoved(this, index, index). The fire... methods will tell the JList itself to repaint.
    The object to store the value might need more info in it then user and dept name, like color to use. And you could then create a cell renderer to enable drawing of the items, otherwise it'll use the toString method to get the string to show.
    Registering a listener, the listener will get the actual object from your internal list as the selected item, so based on that you can do whatever.

  • I'm confused about accessor methods.

    Part of the application I'm developing translates a sequence of strings into a series of hex values. The number of strings will be either 2 or 3. In the cass where there's 3 strings the last would represent an integer or a decimal fraction.
    I have a class Xlate that has 3 translation methods thus:
    public int[] translate(String msg) {};
    public int[] translate(String msg, int val) {};
    public int[] translate(String msg, String aValString) {};
    The problem I have is that the Xlate does not return what is expected when passed an argument via the method signature. If explicitly passed a string sequence it works OK.
    If I pass the argumants... "pause" "21.09876"
    I would expect to see a translation of ... "msg translation array = 76,98,10,20,0A"
    What I get is "msg translation array = FF, FF, FF, FF,FF" which indicates the array has not been amended after initialised.
    This is most likely due to the lack of accessor definitions and their use. HOWEVER, I am confused by such methods.
    I now realise that to pass values setter/getter accessor methods are .
    I think these might be along the lines of the following:
    private String[] commandList; // declares a string variable
    public Xlate() { this(""); }
    public Xlate(String[] msg) { this.commandList = msg[1]; } // holds the name
    public String getCommandStrings() { return this.commandList; } // gets the commandList
    I can't get this to work and know these are not correct.
    I need help to get me moving ahead of this problem. Any help would be appreciated.
    Thanks.
    Philip
    import java.lang.String;
    public class Control {
      public Control() {
       int i;
      static final public Xlate x = new Xlate();
    //  static final public Comms rc = new Comms();
      public static void main(String[] args) {
        String cmd[] =  args;
        for (int i=0;i<args.length;i++)
          cmd=args[i];
    controller(cmd);
    // public static void controller(String portName, String command, String parameter) {
    public static void controller(String[] parameters) {
    Control c = new Control();
    int[] msg ={1,1,1,1,1};
    // Booleans 'pragmaN' are used to select/deselect debug statements
    // though would be embedded in the bytecode
    // so these are not compiler directives
    boolean pragma1=true, pragma2=true, pragma3=true; // toggle using !
    int pVal;
    if (pragma1==true) {
    System.out.print("msg array = ");
    for (pVal=0; pVal<4;pVal++)
         System.out.print(Integer.toHexString(msg[pVal]).toUpperCase() + ",");
    System.out.println(Integer.toHexString(msg[pVal++]).toUpperCase());
    // rc.setupComPort(parameters[0]); // Configure the port referenced
    msg = x.translate("start"); //*********TRANSLATE()************
    msg = x.translate("pause","12.34567"); //*********TRANSLATE()************
    if (pragma2==true) {
    System.out.print("msg translation array = ");
    for (pVal=0; pVal<4;pVal++)
         System.out.print(Integer.toHexString(msg[pVal]).toUpperCase() + ",");
    System.out.println(Integer.toHexString(msg[pVal++]).toUpperCase());
    // rc.writeCmd(msg);
    // Control messages have 3 fixed formats comprising 'a string', 'a string
    // plus an integer' and 'a String plus a String'.
    // For the control messages with an argument a string is constructed before
    // translation by parging the arguments.
    // Do ensure the number of args is greater than 1 and less than 3.
    // Converts integer types to Strings
    String argString="";
    System.out.println("arg len = "+ parameters.length);;
    switch (parameters.length) {
    case 2:
         System.out.println("in switch 2");;
         argString = (parameters[1]);
         msg = x.translate(argString); //*********TRANSLATE()************
         if (pragma3==true) {
         System.out.print("msg translation array = ");
         for (pVal=0; pVal<4;pVal++)
         System.out.print(Integer.toHexString(msg[pVal]).toUpperCase() + ",");
         System.out.println(Integer.toHexString(msg[pVal++]).toUpperCase());
         break;
    case 3:
         if (pragma3==true) {
         System.out.println("in switch 3"); ;
         argString = (parameters[1] + parameters[2]);
         msg = x.translate(argString); //*********TRANSLATE()************
         if (pragma3==true) {
         System.out.print("msg translation array = ");
         for (pVal=0; pVal<4;pVal++)
         System.out.print(Integer.toHexString(msg[pVal]).toUpperCase() + ",");
         System.out.println(Integer.toHexString(msg[pVal++]).toUpperCase());
         break;
    default:
         System.out.println("Argument length error");
    break;
    // rc.writeCmd(msg);
    import java.text.*;
    import java.text.StringCharacterIterator; // required for CharacterIterator class
    public class Xlate {
    private String[] commandList; // declares a string variable
    public Xlate() { this(""); }
    public Xlate(String[] msg) { this.commandList = msg[1]; } // holds the name
    public String getCommandStrings() { return this.commandList; } // gets the commandList
    // These methods form a basic translation mechanism used as proof
    public int[] translate(String msg) {
    int[] paramList = {
         0xFF, 0xFF, 0xFF, 0xFF, 0xFF}; //initialise this array
    //Power On and Off controls
    if (msg == "start") {
    paramList = new int[] {
         0xFF, 0xFF, 0xFF, 0x01, 0x20};
    if (msg == "stop") {
    paramList = new int[] {
         0xFF, 0xFF, 0xFF, 0x00, 0x20};
    return (paramList);
    public int[] translate(String msg, int val) {
    int[] paramList = {};
    int pVal;
    // Memory recall with memory ID.
    if (msg == "M") { // Recall memory
    paramList = new int[] {
         0xFF, 0xFF, 0xFF, 0xFF, 0x02};
    // stuff the argument in to the paramList array
    paramList[3] = Integer.decode(Integer.toHexString(val)).shortValue();
    return (paramList);
      public int[] translate(String msg, String aValString) {
    // Convert the string
        int i, j, k;
        int index = 0, c = 0;
        int[] p, paramList = {};
        final StringBuffer result = new StringBuffer(); // only ever one buffer
        char character;
        if (msg == "pause") {
          paramList = new int[] {
           0xFF, 0xFF, 0xFF, 0xFF, 0x0A};
    // The period character is the axle where operations centre...
    // working from the left most position index until period is found.
    // append chars to result string en route.
    // if period then stop - this is the integer part
        StringCharacterIterator sci = new StringCharacterIterator(aValString);
        result.append('0'); // a fudge to pad out the resulting string
        character = sci.current();
        while (character != '.') {
          //char is not a period so append to buffer
          result.append(character);
          character = sci.next();
        character = sci.next();
    // working from the position of 'the period character' append chars to result string en route.
    // stop at the end having bound the fraction part
        while (character != StringCharacterIterator.DONE) {
          result.append(character);
          character = sci.next();
        aValString = result.toString(); // save the result
        sci = new StringCharacterIterator(aValString);
        String[] part = {
         "00", "00", "00", "00"}; // array index ordered 0 to 3 from left to right
        result.delete(0, result.capacity()); // initialise the StringBuffer result
        character = sci.first();
        for (index = 0; index <= 3; ++index) {
          for (i = 0; i <= 1; ++i) {
         if (character != StringCharacterIterator.DONE) {
           result.append(character);
           character = sci.next();
         else {
           result.append('0');
          part[index] = result.toString();
          result.delete(0, result.capacity()); // initialise the StringBuffer result
    // the sequence handles the conversion of decimal to packed BCD for transmission
        for (k = 0; k <= 3; k++) {
          // cast the String in the array part indexed by k to an int
          i = Integer.parseInt(part[k]);
          for (j = 0; j < 10; j++) {
         if ( (i >= (j * 10)) & (i < ( (j + 1) * 10))) {
           paramList[k] = (j * 0x10 + (i - (j * 10)));
        return (paramList);

    Sorry, this is way too much to look at (at least for me). Please create a small test function that fails & post the formatted code. In doing this, you may even spot the problem yourself!

  • Using JOptionPane to exit program & Using toString method

    Hello,
    In my program I have to use a toString method below
    public String toString(Hw1NCBEmployee[] e)
            String returnMe = String.format(getStoreName() + "\n" + getStoreAddress() + "\n" + getCityState() +  "\nYou have " + getEmpCount() + "employee(s)");
            return returnMe;
    }Now, at first, when I initially tested my code, it was working just fine, printing out the right way
    Point is -- now that Im practically finished with my program, and am going back and running it - calling the toString method gives me the address rather than the information . . . Can anyone help me with this issue??
    Also, Im using JOptionPane to display everything, but -- at first, it worked fine, then (around the same time I started having the above problem) it stopped exiting the do-while loop:
    while(go)
                 int option = JOptionPane.showConfirmDialog(null, "Do you want to enter employee information?", "Welcome!", JOptionPane.YES_NO_OPTION);
                     if(option == JOptionPane.NO_OPTION)
                        go = false;  //exit loop
            

    ncjb wrote:
    well, for the toString - I have to print out the info inside the array -- am I right in thinking that the only way to do this is to pass in the array ??If the array is part of the class then there is no need to pass it as a parameter. If it is being passed in from outside the class then I have to question your design. Why should class X being formatting data that is not a representation of itself?
    and i have 2 other files that go with this program . . . I just want to know if there is a way to make sure that when the user presses the NO option, it will exit the loop -- the piece of code you see if apart of an entire method (not long) -- do you want me to include this??You read that link I provided REAL quick!

  • Socket Programing in J2ME - Confused with Sun Sample Code

    Hai Everybody,
    I have confused with sample code provided by Sun Inc , for the demo of socket programming in J2ME. I found the code in the API specification of J2ME. The code look like :-
    // Create the server listening socket for port 1234
    ServerSocketConnection scn =(ServerSocketConnection) Connector.open("socket://:1234");
    where Connector.open() method return an interface Connection which is the base interface of ServerSocketConnection. I have confused with this line , is it is possible to cast base class object to the derived class object?
    Plese help me in this regards
    Thanks in advance
    Sulfikkar

    There is nothing to be confused about. The Connector factory creates an implementation of one of the extentions of the Connection interface and returns it.
    For a serversocket "socket://<port>" it will return an implementation of the ServerSocketConnection interface. You don't need to know what the implementation looks like. You'll only need to cast the Connection to a ServerSocketConnection .

  • JSP Tags, EL and toString() method

    Hi,
    I want to pass a Java object to a custom tag via EL, but am finding that since the class has a toString() method, EL automatically converts the class to a string using the toString method. Consequently, I get an error because the string cannot be cast back to the parent object in the tag handler class.
    I played around with a dummy class and found that if the toString() method wasn't defined, EL would pass the object as is without converting to a string.
    Is there some reason for this behaviour and is there some way I can get around this without having to remove the toString() method ? The object I am trying to process is from an external library, so I can't modify it.
    Thanks for any tips on this.
    Paul Samuel

    My initial guess was that you hadn't defined the type of the attribute, and it was defaulting to String as a result. Now that I've seen the tld file thats obviously not the cause.
    Next guess: EL evaluation is disabled, and it is interpreting ${model.results} as a string, rather than evaluating it.
    1 - What happens if you just put ${1 + 1} onto a JSP page. Does it print ${1 + 1} or evaluate it as 2?
    2 - What server are you using? What version? Which J2EE spec does it support?
    You can use the following JSP snippet to confirm this info:
    <h2> Server Info</h2>
    Server info = <%= application.getServerInfo() %> <br>
    Servlet engine version = <%=  application.getMajorVersion() %>.<%= application.getMinorVersion() %><br>
    Java version = <%= System.getProperty("java.vm.version") %><br>
    Session id = <%= session.getId() %><br>3 - What version is your web.xml declared as? 2.3 or 2.4?
    4- If you have a Servlet2.4/JSP2.0 container (eg Tomcat 5), try putting the following on your page and see if it works
    <%@ page isELIgnored="false" %>
    http://forum.java.sun.com/thread.jspa?threadID=629437&tstart=0
    Cheers,
    evnafets

  • Problem Using toString method from a different class

    Hi,
    I can not get the toString method to work from another class.
    // First Class Separate file MyClass1.java
    public class MyClass1 {
         private long num1;
         private double num2;
       public MyClass1 (long num1, double num2) throws OneException, AnotherException {
            // Some Code Here...
        // Override the toString() method
       public String toString() {
            return "Number 1: " + num1+ " Number 2:" + num2 + ".";
    // Second Class Separate file MyClass2.java
    public class MyClass2 {
        public static void main(String[] args) {
            try {
               MyClass1 myobject = new MyClass1(3456789, 150000);
               System.out.println(myobject);
             } catch (OneException e) {
                  System.out.println(e.getMessage());
             } catch (AnotherException e) {
                  System.out.println(e.getMessage());
    }My problem is with the System.out.println(myobject);
    If I leave it this way it displays. Number 1: 0 Number 2: 0
    If I change the toSting method to accept the parameters like so..
    public String toString(long num1, double num2) {
          return "Number 1: " + num1 + " Number 2:" + num2 + ".";
       }Then the program will print out the name of the class with some garbage after it MyClass1@fabe9. What am I doing wrong?
    The desired output is:
    "Number 1: 3456789 Number 2: 150000."
    Thanks a lot in advance for any advice.

    Well here is the entire code. All that MyClass1 did was check the numbers and then throw an error if one was too high or too low.
    // First Class Separate file MyClass1.java public class MyClass1 {
         private long num1;
         private double num2;
         public MyClass1 (long num1, double num2) throws OneException, AnotherException {              
         // Check num2 to see if it is greater than 200,000
         if (num2 < 10000) {
                throw new OneException("ERROR!:  " +num2 + " is too low!");
         // Check num2 to see if it is greater than 200,000
         if (num2 > 200000) {
                throw new AnotherException ("ERROR!:  " +num2 + " is too high!");
         // Override the toString() method
         public String toString() {
              return "Number 1: " + num1+ " Number 2:" + num2 + ".";    
    // Second Class Separate file MyClass2.java
    public class MyClass2 {
        // Main method where the program begins.
        public static void main(String[] args) {
            // Instantiate first MyClass object.
            try {
               MyClass1 myobject = new MyClass1 (3456789, 150000);
               // if successful use MyClass1 toString() method.
               System.out.println(myobject);
                         // Catch the exceptions within the main method and print appropriate
                         // error messages.
             } catch (OneException e) {
                  System.out.println(e.getMessage());
             } catch (AnotherException e) {
                  System.out.println(e.getMessage());
             }I am not sure what is buggy. Everything else is working fine.

  • Overriding toString() method

    hello all,
    in the following class how toString() is overriding?
    class Box {
        public Box(){
        public String toString(){
            return "Hello";
        public static void main(String args[]){
            System.out.println(new Box());
    }even though i am not extending anything.
    how the toString() method of String class is overriding here?
    is it due to Object class?
    thanks
    daya

    even though i am not extending anything.
    how the toString() method of String class is
    overriding here?
    is it due to Object class?Yes, thats it exactly. Even when you do not extend and class, by default every class inherits from the Object class. Since toString is defined in the Object class, you override it when you defing toString with the same signature.

  • Using a toString() method to round decimals

    I've been working on this project for school, building a class which models cartesian coordinates and can also convert them to polar coordinates. After much work I have a working product with some time to spare. Theres a small amount of extra credit to be gained if i can use toString() methods to manipulate my results to be exactly to two decimal places.
    I've been looking at the api documentation, which is what my teacher suggested, but its a little tough for a rookie like me to wade through. A point in the right direction or any help would be greatly apreciated.
    Thanks in advance

    I understand, I just dont want yall to feel like youre doing all the work for me.
    Anyways i searched google and using what i saw on this site
    http://www.particle.kth.se/~lindsey/JavaCourse/Book/Part1/Tech/Chapter05/decimalFormat.html
    adapted what i could to my class and came up with this
    String fmt = "0.00";
      DecimalFormat df = new DecimalFormat( fmt );
      String str_x = df.format(x);
      String str_y = df.format(y);
      public String toString()
        return "( " + str_x + ", " + str_y + " )";
      }x and y are the instance variables im using for my class: Coord
    when i try to compile i get these two error messages:
    Coord.java:133: cannot find symbol
    symbol : class DecimalFormat
    location: class Coord
    DecimalFormat df = new DecimalFormat( fmt );
    ^
    Coord.java:133: cannot find symbol
    symbol : class DecimalFormat
    location: class Coord
    DecimalFormat df = new DecimalFormat( fmt );
    ^
    I assume these errors mean my syntax is off but hopefully im headed in the right direction.

  • Overiding the toString method

    If I have a method which takes an array of strings as the first argument and a string as the second argument.
    I will compare the string to each index in the passed in array and add the smaller strings to an arraylist.
    firstly to return an ArrayList, what type of method would it be, String?
    Then how is the toString method overridden to print out the ArrayList if the ArrayList could vary depending on the passed in arguments?
    ;)

    Encephalopathic wrote:
    Implode wrote:
    If I want to print out an ArrayList using a for loop, the toString method needs to be overridden?No, not at all. You simply loop through the ArrayList and println each element. Now if the elements are complex objects, then the toString method of the class that the elements are composed of may need a toString override.
    I had to do that with previous examples.Code is worth a thousand words. What do you mean here? Did what?
    Yeah, sorry, I guess I never explained properly. I know how to override toString method, (totally serperate question)but what if the ArrayList was containing object references , and the ArrayList was built depending on arguments passed to a method , how would the toString be overridden then?Again, you would need to have a toString override of the objects held by the ArrayList, not the ArrayList itself.
    For e.g.,
    import java.util.ArrayList;
    import java.util.Random;
    public class MyFoo {
    private String text;
    private int value;
    public MyFoo(String text, int value) {
    super();
    this.text = text;
    this.value = value;
    @Override // here's the necessary toString override
    public String toString() {
    return text + ": " + value;
    public static void main(String[] args) {
    String[] strings = {"Mon", "Tues", "Wed", "Thurs", "Fri"};
    Random random = new Random();
    ArrayList<MyFoo> fooList = new ArrayList<MyFoo>();
    for (String text : strings) {
    fooList.add(new MyFoo(text, random.nextInt(100)));
    // to print out in a for loop:
    for (MyFoo myFoo : fooList) {
    System.out.println(myFoo);
    }Edited by: Encephalopathic on Nov 15, 2009 9:11 AMI did override toString using complex objects in previous examples(university assignments).
    Thanks for the help. Forget the question. It was sidetrack.
    Edited by: Implode on Nov 15, 2009 9:23 AM

  • Polymorphism with Overloaded Methods

    I am running into a problem when I try to leverage java��s polymorphism with overloaded Methods. Basically, what I am trying to do is iterate through a generic list of properties and call the correct overloaded method on each one based on the type of containing object.
    Here is the general code (4 classes)
    AbstractCronJob �� EmailCronJob
    BaseProperty �� SubjectLineProperty
    public abstract class BaseProperty implements CronPropertyExecutable{
        public BaseProperty() {
            super();
       public void execute(AbstractCronJob job) {
           System.out.println( "executing on abstract cron job" ) ;
    public class SubjectLineProperty extends BaseProperty {
        public SubjectLineProperty() {
            super();
        public final void execute( EmailCronJob emailCronJob ) {
            System.out.println( "executing on email cron job" ) ;
    public abstract class AbstractCronJob {
        protected int _id ;
        protected PropertyList _propertyList ;
        public AbstractCronJob( int id ) {
            super();
            _id = id ;
            _propertyList = new PropertyList() ;
        protected void createProperties() {
            //fill in with factory crap
            _propertyList.add( new SubjectLineProperty() ) ;
        protected abstract void executeProperties();
        protected abstract void run() ;
        public void execute() {
            createProperties() ;
            executeProperties() ;
            run() ;
    public class EmailCronJob extends AbstractCronJob {
        public EmailCronJob( int id ) {
            super( id ) ;   
        /* (non-Javadoc)
         * @see com.reged.cron.AbstractCronJob#run()
        protected void run() {
            //send email
        protected void executeProperties() {
            //we had this as abstract...unless I'm missing something, we can do this
            //in this class instead of pushing it down
            Iterator iter = _propertyList.iterator() ;
            while ( iter.hasNext() ) {
                //safe cast
                BaseProperty baseProperty = ( BaseProperty ) iter.next() ;
                baseProperty.execute( this ) ;
    }Okay, here is the problem that I am running into. The EmailCronJob knows that it has a list of properties, it doesn't know what type of properties it as. So when it iterates through its property list it upcasts then to the BaseProperty parent class. Then it calls the execute method on each property passing in itself.
    I thought that the execute(EmailCronJob job) method in SubjectLineProperty would be executed since the overloaded method with the mailCronJob parameter lives in that class, instead I am finding that the execute(AbstractCronJob job) method in the BaseProperty class is eing exercised.
    I am confused on why this doesn't work. Does polymorphism work with overloaded methods or just overridden methods?
    Thanks!

    We can think about it based on suppositions, satisfactory explanations, and based on OO design.
    According to the experience from the code above, we can suppose that, at runtime, the virtual machine looks for an exact identical signature of an method to perform the overriding.
    But, why does it work in that way? Is there any good justification, or is it just a implementation decision?
    I think there is a good justification.
    Let me get the Object.equals() method as an example, and let�s make an analogy with the code above. According to our conclusions from the experience above, that we suppose are right and should work, but actually they should not work, in order to use the equals() method, we can simply do this:
    class TheClass {
      private int whatever;
      public TheClass(int param) {
        whatever = param;
      //notice that the param is not Object
      public boolean equals(TheClass param) {
        //we don�t need either to cast to TheClass or
        //verify if the param is an instance of TheClass
        if (this == param) return false;
        if (this.whatever == param.whatever) return true;
        else return false;
    }Apparently, this equals() method above is more efficient, and it does make sense, too, and it would be considered a good and logic implementation of equals() method. Although, these conclusions are wrong, if you consider some OO concepts that are being broken here.
    equals() method is defined in Object class as an contract, like an interface. It says that this method must receive an Object param. And according to this contract, two instances of Object can use this method. You have to obey this contract, because it is Oriented Object Programming.
    If you use equals method without passing Object as an parameter, but passing other different class (like TheClass, in my example), you would not obey the contract, that says that two instances of Object can use this method. Try to do this:
    public static void main(String[] args) {
        TheClass theClass1 = new TheClass(1);
        TheClass theClass2 = new TheClass(1);
        //Good, more or less, because our objective, that is,
        //calling the customized equals(), will be performed.
        System.out.println(theClass1.equals(theClass2));
        String str = "blah";
        //oops! The customized equals() method will not
        //be called this time
        System.out.println(theClass1.equals(str));
        Object obj1 = theClass1;
        Object obj2 = theClass2;
        //Again, the customized equals() method will not
        //be called this time. Thanks God it works in this way!
        //Because if the customized equals() method
        //could be called here, the "OO law"
        //and the "contract" of equals method
        //defined in Object class would be broken
        System.out.println(obj1.equals(obj2));
    }Therefore, I think Java working in this way is good, because it obligates us to "obey the laws", in certain way.

  • Confusion with Image/BufferedImage

    Hello,
    I'm trying to write an applet that displays and modifies local image files (gif). I'm running into some confusion with the different image APIs and drawing methods though.
    I want to read the files, display them, and then create new images from sections of the original ones. I wrote an applet that succesfully loads and displays files as Image objects, but then I saw that BufferedImage has a method getSubImage() that I thought I could use to create the new images.
    But my problem is that even without manipulating the images, I can't get them to display as BufferedImages. Here's the code, where I try to display the series of images twice, once as Image, once as BufferedImage, but the BI come out as black squares.
    public class myapplet extends Applet
         BufferedImage[] img = new BufferedImage[NUM_PICS];
         Image[] im = new Image[NUM_PICS];
         public void init()
              Toolkit t = Toolkit.getDefaultToolkit();
              Graphics2D bg;
              MediaTracker tracker = new MediaTracker (this);
              for(int i = 0;i<NUM_PICS;i++)
                   try
                        im[i] = t.getImage(gen.getLogo());
    //the getLogo method is from a class I wrote -
    //it returns a string with a filename
                   catch(Exception e)
                        System.out.println("ERROR: "+e.getMessage());
                   img[i] = new BufferedImage(70, 70,BufferedImage.TYPE_INT_RGB);
    bg = img[i].createGraphics();
    bg.drawImage(im[i],0,0,this);
         public void paint(Graphics g)
              Graphics2D g2 = (Graphics2D)g;
              for(int i=0;i<NUM_PICS;i++)
                   g.drawImage(im[i],10,i*70,this);
                   g2.drawImage(img[i],null,80,i*70);
    Any help would be great.

    You have to use the MediaTracker before drawing the image onto the BufferedImage:
    try {
    im[i] = t.getImage(gen.getLogo());
    tracker.addImage(im[i], i);
    tracker.waitForID(i);

  • RE: (forte-users) Confusion with return event

    Samer,
    The return event is delivered to the calling task, which is the window in
    your first test. It is not deliverd to the event loop of the service object
    unless the call to the processor originated in the event loop, which is the
    case in your second test. The output you get from the server is exactly as I
    would expect.
    You need the following code in you client:
    event loop
    postregister
    SomeService1.StartImmediate();
    when SomeService1.Proc.ProcessEvent_return do
    task.Part.Logmgr.Putline('ProcessEvents_return');
    when SomeService1.Proc.ProcessEvent_exception do
    task.Part.Logmgr.Putline('ProcessEvents_exception');
    end event;
    Note that this logoutput will not be written to a logfile, but will appear
    in the logwindow which is opened when you start a client application.
    Pascal Rottier
    Atos Origin Nederland (BAS/West End User Computing)
    Tel. +31 (0)10-2661223
    Fax. +31 (0)10-2661199
    E-mail: Pascal.Rottiernl.origin-it.com
    ++++++++++++++++++++++++++++
    Philip Morris (Afd. MIS)
    Tel. +31 (0)164-295149
    Fax. +31 (0)164-294444
    E-mail: Rottier.Pascalpmintl.ch
    -----Original Message-----
    From: Samer Kanjo [mailto:skanjoyahoo.com]
    Sent: Thursday, January 18, 2001 1:54 AM
    To: ForteUsers
    Subject: (forte-users) Confusion with return event
    I have observed some odd behavior when attempting to
    catch a return event for a method invoked using start
    task. I provided the primary classes I used during my
    test and some output produced by those classes at the
    bottom of this message.
    The SomeService1 class is used to create an
    environment visible service object and the Processor
    class is one of its members. The Processor class
    starts processing when one of two things happens: the
    SomeService1 timer ticks off 10 seconds or when
    SomeService1.StartImmediate is called directly by
    another entity. Either way StartImmediate is called to
    start processing.
    The provided output is the result of starting a test
    application and invoking StartImmediate from another
    object (I used a window) and then observing what
    happens when the timer ticks. As you can see the
    invocation from the window did not result in the
    return event being received. However, the return event
    was received when the timer ticked.
    According to the Forte documentation a return event
    will only be posted to the parent task's event queue.
    Since I am making a cross partition call, the window
    and service object are not really in the same task
    (Unless my assumption is wrong). That would explain
    why the window did not cause a return event to be
    generated but was an event generated but not caught
    and if so where did the event go?
    In SomeService2 class I added an event StartProcessing
    and moved the code from StartImmediate to the
    StartProcessing event case in the event loop and
    simply posted the StartProcessing event in
    StartImmediate. I performed the same test I used when
    testing SomeService1. The Traceback output is
    identical for the window invocation but the return
    event is received this time! Why?
    It seems that to guarantee the receipt of a return
    event an asynchronous task must be initiated from
    within an event loop. Is this correct?
    I do not understand this behavior does someone have
    any thoughts on this? How can you guarantee the
    receipt of a return event?
    Samer Kanjo
    OUTPUT FROM SOMESERVICE1
    StartTaskTest_cl0: processing loop listening
    StartTaskTest_cl0:
    Traceback:
    SomeService.StartImmediate at line 1
    TestWin.Display at line 4
    C++ Method(s)
    UserApp.Run at offset 105
    StartTaskTest_cl0:
    StartTaskTest_cl0: Start processing...
    StartTaskTest_cl0: Processing complete.
    StartTaskTest_cl0:
    Traceback:
    SomeService.StartImmediate at line 1
    SomeService.ProcessingLoop at line 9
    StartTaskTest_cl0:
    StartTaskTest_cl0: Start processing...
    StartTaskTest_cl0: Processing complete.
    StartTaskTest_cl0: ProcessEvents_return
    OUTPUT FROM SOMESERVICE2
    StartTaskTest_cl0: processing loop listening
    StartTaskTest_cl0:
    Traceback:
    SomeService2.StartImmediate at line 1
    TestWin.Display at line 4
    C++ Method(s)
    UserApp.Run at offset 105
    StartTaskTest_cl0:
    StartTaskTest_cl0: Start processing...
    StartTaskTest_cl0: Processing complete.
    StartTaskTest_cl0: ProcessEvents_return
    StartTaskTest_cl0:
    Traceback:
    SomeService2.StartImmediate at line 1
    SomeService2.ProcessingLoop at line 9
    StartTaskTest_cl0:
    StartTaskTest_cl0: Start processing...
    StartTaskTest_cl0: Processing complete.
    StartTaskTest_cl0: ProcessEvents_return
    SOMESERVICE1 CLASS
    begin CLASS;
    class SomeService1 inherits from Framework.Object
    has public attribute proc: StartTaskTest.Processor;
    has public attribute processing: Framework.boolean;
    has public method Init;
    has public method ProcessingLoop;
    has public method StartImmediate;
    has property
    shared=(allow=off, override=on);
    transactional=(allow=off, override=on);
    monitored=(allow=off, override=on);
    distributed=(allow=on, override=on, default=off);
    end class;
    method SomeService1.Init
    begin
    super.Init();
    processing = FALSE;
    proc = new;
    start task ProcessingLoop();
    end method;
    method SomeService1.ProcessingLoop
    begin
    timer : Timer = new;
    timer.tickInterval = 10000;
    event loop
    task.part.logmgr.putline('processing loop
    listening');
    timer.isActive = TRUE;
    when timer.tick do
    StartImmediate();
    when proc.ProcessEvents_return do
    task.part.logmgr.putline('ProcessEvents_return');
    processing = FALSE;
    when proc.ProcessEvents_exception do
    task.part.logmgr.putline('ProcessEvents_exception');
    processing = FALSE;
    when task.shutdown do
    exit;
    end event;
    end method;
    method SomeService1.StartImmediate
    begin
    task.part.logmgr.putline(task.traceBack());
    processing = TRUE;
    start task proc.ProcessEvents() where completion =
    event;
    end method;
    end CLASS;
    SOMESERVICE2 CLASS
    begin CLASS;
    class SomeService2 inherits from Framework.Object
    has public attribute proc: StartTaskTest.Processor;
    has public attribute processing: Framework.boolean;
    has public event StartProcessing;
    has public method Init;
    has public method ProcessingLoop;
    has public method StartImmediate;
    has property
    shared=(allow=off, override=on);
    transactional=(allow=off, override=on);
    monitored=(allow=off, override=on);
    distributed=(allow=on, override=on, default=off);
    end class;
    method SomeService2.Init
    begin
    super.Init();
    processing = FALSE;
    proc = new;
    start task ProcessingLoop();
    end method;
    method SomeService2.ProcessingLoop
    begin
    timer : Timer = new;
    timer.tickInterval = 10000;
    event loop
    task.part.logmgr.putline('processing loop
    listening');
    timer.isActive = TRUE;
    when timer.tick do
    StartImmediate();
    when self.StartProcessing do
    processing = TRUE;
    start task proc.ProcessEvents() where completion =
    event;
    when proc.ProcessEvents_return do
    task.part.logmgr.putline('ProcessEvents_return');
    processing = FALSE;
    when proc.ProcessEvents_exception do
    task.part.logmgr.putline('ProcessEvents_exception');
    processing = FALSE;
    when task.shutdown do
    exit;
    end event;
    end method;
    method SomeService2.StartImmediate
    begin
    task.part.logmgr.putline(task.traceBack());
    post StartProcessing;
    end method;
    end CLASS;
    PROCESSOR CLASS
    begin CLASS;
    class Processor inherits from Framework.Object
    has public method Init;
    has public method ProcessEvents where completion =
    (return = ProcessEvents_return, exception =
    ProcessEvents_exception);
    has property
    shared=(allow=off, override=on);
    transactional=(allow=off, override=on);
    monitored=(allow=off, override=on);
    distributed=(allow=off, override=on);
    end class;
    method Processor.Init
    begin
    super.Init();
    end method;
    method Processor.ProcessEvents
    begin
    task.part.logmgr.putline('Start processing...');
    task.Delay(msecs = 1500);
    task.part.logmgr.putline('Processing complete.');
    end method;
    end CLASS;
    For the archives, go to: http://lists.xpedior.com/forte-users and use
    the login: forte and the password: archive. To unsubscribe, send in a new
    email the word: 'Unsubscribe' to: forte-users-requestlists.xpedior.com

    Yes, you're right. The return event is queued until the moment that you
    actually enter an eventloop. I stand corrected.
    Pascal Rottier
    Atos Origin Nederland (BAS/West End User Computing)
    Tel. +31 (0)10-2661223
    Fax. +31 (0)10-2661199
    E-mail: Pascal.Rottiernl.origin-it.com
    ++++++++++++++++++++++++++++
    Philip Morris (Afd. MIS)
    Tel. +31 (0)164-295149
    Fax. +31 (0)164-294444
    E-mail: Rottier.Pascalpmintl.ch
    -----Original Message-----
    From: Adamek, Zenon [mailto:ZAdamekpurolator.com]
    Sent: Thursday, January 18, 2001 6:13 PM
    To: Rottier, Pascal
    Cc: 'forte-userslists.xpedior.com'
    Subject: RE: (forte-users) Confusion with return event
    I think it is always safe to use start task with where complition = event
    clause before event loop. The reason is described in Forte Help in the
    Complition Clause index:
    "Requesting the return and exception events automatically registers the
    events for the calling task. When the asynchronous method completes or
    terminates, Fort&eacute; adds the appropriate event to the calling task's event
    queue.
    This registration is unlike the event registration for the event statement.
    In the event statement, the event is registered just before the event
    statement is ready to process the event. In the start task statement, the
    return and exception events are registered when the task is started, even
    though it can be much later on that your application is prepared to wait for
    those events. Therefore, only the "parent" task that executes the start task
    statement is registered for the completion event of the started task."
    and some comments from "Forte Performance and Patterns" page 18:
    "When you use the where completion = event clause in the start task
    statement, Forte automatically buffer the return event until you register
    for it. Therefore, you do not need to worry about the child task completing
    before you register for its return event".
    Regards,
    Zenon
    -----Original Message-----
    From: Rottier, Pascal [SMTP:Rottier.Pascalpmintl.ch]
    Sent: Thursday, January 18, 2001 11:16 AM
    To: 'Samer Kanjo'; ForteUsers
    Subject: RE: (forte-users) Confusion with return event
    Yes, if you want the eventloop of the service object to be informed when
    the
    method on the processor class is invoked, regardless of who invoked it,
    then
    you should simply post an event as the last statement inside the method on
    the processor class.
    The return events are only used to inform a partent task that a child-task
    has completed. So, only the calling task receives the event, only if the
    calling task is inside an event-loop at the moment the child-task
    terminates
    and only if there really is a child task (method started using "start task
    Note, that the calling task doesn't have to be inside an event loop when
    the
    asynchronous call is made. It has to be inside an eventloop when the
    asynchronous task terminates. The following piece of code works just as
    well:
    SomeService1.StartImmediate();
    self.DoSomeOtherStuff();
    event loop
    when SomeService1.Proc.ProcessEvent_return do
    task.Part.Logmgr.Putline('ProcessEvents_return');
    when SomeService1.Proc.ProcessEvent_exception do
    task.Part.Logmgr.Putline('ProcessEvents_exception');
    end event;
    However, if the asynchronous task started from within "StartImmediate"
    finishes before the client gets a chance to enter its event loop, then
    you're too late to catch the event. That's why it's safer to use the
    "postregister" function, which makes sure a certain action is not started
    untill all events from the event loop have been registered.
    Pascal Rottier
    Atos Origin Nederland (BAS/West End User Computing)
    Tel. +31 (0)10-2661223
    Fax. +31 (0)10-2661199
    E-mail: Pascal.Rottiernl.origin-it.com
    ++++++++++++++++++++++++++++
    Philip Morris (Afd. MIS)
    Tel. +31 (0)164-295149
    Fax. +31 (0)164-294444
    E-mail: Rottier.Pascalpmintl.ch
    -----Original Message-----
    From: Samer Kanjo [mailto:skanjoyahoo.com]
    Sent: Thursday, January 18, 2001 5:04 PM
    To: ForteUsers
    Subject: RE: (forte-users) Confusion with return event
    Pascal,
    So you are confirming that a return event can only be
    received in an event loop if a task is started from
    within that event loop.
    After making your proposed changes I was able to
    receive the return event in the window.
    I originally wanted the SomeService event loop to
    always receive the return event regardless of whether
    or not StartImmediate is called by some other entity
    or called when the timer ticks. It seems that the only
    way to do this is with events. Is that correct?
    Thank you for insight,
    Samer Kanjo
    --- "Rottier, Pascal" <Rottier.Pascalpmintl.ch>
    wrote:
    Samer,
    The return event is delivered to the calling task,
    which is the window in
    your first test. It is not deliverd to the event
    loop of the service object
    unless the call to the processor originated in the
    event loop, which is the
    case in your second test. The output you get from
    the server is exactly as I
    would expect.
    You need the following code in you client:
    event loop
    postregister
    SomeService1.StartImmediate();
    when SomeService1.Proc.ProcessEvent_return do
    task.Part.Logmgr.Putline('ProcessEvents_return');
    when SomeService1.Proc.ProcessEvent_exception do
    task.Part.Logmgr.Putline('ProcessEvents_exception');
    end event;
    Note that this logoutput will not be written to a
    logfile, but will appear
    in the logwindow which is opened when you start a
    client application.
    Pascal Rottier
    Atos Origin Nederland (BAS/West End User Computing)
    Tel. +31 (0)10-2661223
    Fax. +31 (0)10-2661199
    E-mail: Pascal.Rottiernl.origin-it.com
    ++++++++++++++++++++++++++++
    Philip Morris (Afd. MIS)
    Tel. +31 (0)164-295149
    Fax. +31 (0)164-294444
    E-mail: Rottier.Pascalpmintl.ch--
    For the archives, go to: http://lists.xpedior.com/forte-users and use
    the login: forte and the password: archive. To unsubscribe, send in a new
    email the word: 'Unsubscribe' to: forte-users-requestlists.xpedior.com
    For the archives, go to: http://lists.xpedior.com/forte-users and use
    the login: forte and the password: archive. To unsubscribe, send in a new
    email the word: 'Unsubscribe' to: forte-users-requestlists.xpedior.com

Maybe you are looking for

  • Questions on LOV

    I have two questions on LOV. 1. How to sort the elements in an LOV? I could not find any property in Designer to specify the order. 2. How do I prepopulate the "Find" field of an LOV programmatically? Please help!

  • RAID disk not detected by Windows XP

    I have installed a single disk connected to the RAID controller on my K7T266 Pro2-R Mobo. The RAID controller (that is enabled in BIOS) detects the disk, reports a correct size and reports it as "Functional". I have used the BIOS utility to assign an

  • Sap query report-selection screen modification

    Hi I  have created a SAP query report using the logical database KDF ,the selection screen was created automatically.For vendor report open item and Cleared item Push button would be there in FBL1N but here it only displays Open key date,clearing dat

  • Best use of connection pool

    hi all, i have some confusion if someone have good suggetions for me. i make an connection pool class, and in that package and subpackages i have different class files which do interact with DB thus in whole class files i want to use that same connec

  • GR durng final inspection - single inspection lot

    Hello Friends, In material master there is a key that control inspection lot creation during GR from purchasing is there any similar key for production too Like below For each purchase order item, batch and storage location Thanks & Regards Raj