tags:

views:

5878

answers:

6

I wish to print a stack object as nicely as the Eclipse debugger does, ie [1,2,3] etc. printing it like so out = "outout:"+stack doesn't return this nice result.

Just to clarify. I'm talking about Java's builtin collections I can't override their toString.

How can get the nice printable version of the stack?

+15  A: 

You could convert it to an array and then print that out with Arrays.toString(Object[]):

System.out.println(Arrays.toString(stack.toArray()));
Zach Langley
A: 

If this is your own collection class rather than a built in one, you need to override its toString method. Eclipse calls that function for any objects for which it does not have a hard-wired formatting.

Uri
And how does eclipse format those classes w/ hard-wired formatting? That's what I'm looking for.
Elazar Leibovich
+3  A: 

Implement toString() on the class.

I recommend the Apache Commons ToStringBuilder to make this easier. With it, you just have to write this sort of method:

public String toString() {
     return new ToStringBuilder(this).
       append("name", name).
       append("age", age).
       toString(); 
}

In order to get this sort of output:

Person@7f54[name=Stephen,age=29]

There is also a reflective implementation.

Chinnery
ToStringBuilder is usually more applicable for beans and objects that carry information, less so for complex data structures. If the stack object doesn't print all stored items, this won't help.
Uri
+2  A: 

I agree with the above comments about overriding toString() on your own classes (and about automating that process as much as possible).

For classes you didn't define, you could write a ToStringHelper class with an overloaded method for each library class you want to have handled to your own tastes:

public class ToStringHelper {
    //... instance configuration here (e.g. punctuation, etc.)
    public toString(List m) {
        // presentation of List content to your liking
    }
    public toString(Map m) {
        // presentation of Map content to your liking
    }
    public toString(Set m) {
        // presentation of Set content to your liking
    }
    //... etc.
}

EDIT: Responding to the comment by xukxpvfzflbbld, here's a possible implementation for the cases mentioned previously.

package com.so.demos;

import java.util.List;
import java.util.Map;
import java.util.Set;

public class ToStringHelper {

    private String separator;
    private String arrow;

    public ToStringHelper(String separator, String arrow) {
        this.separator = separator;
        this.arrow = arrow;
    }

   public String toString(List<?> l) {
        StringBuilder sb = new StringBuilder("(");
        String sep = "";
        for (Object object : l) {
            sb.append(sep).append(object.toString());
            sep = separator;
        }
        return sb.append(")").toString();
    }

    public String toString(Map<?,?> m) {
        StringBuilder sb = new StringBuilder("[");
        String sep = "";
        for (Object object : m.keySet()) {
            sb.append(sep)
              .append(object.toString())
              .append(arrow)
              .append(m.get(object).toString());
            sep = separator;
        }
        return sb.append("]").toString();
    }

    public String toString(Set<?> s) {
        StringBuilder sb = new StringBuilder("{");
        String sep = "";
        for (Object object : s) {
            sb.append(sep).append(object.toString());
            sep = separator;
        }
        return sb.append("}").toString();
    }

}

This isn't a full-blown implementation, but just a starter.

joel.neely
I know that DP. But how can I easily print them in a readable format?
Elazar Leibovich
A: 

System.out.println(Collection c) already print any type of collection in readable format. Only if collection contains user defined objects , then you need to implement toString() in user defined class to display content.

Shekhar
A: 

Just Modified the previous example to print even collection containing user defined objects.

public class ToStringHelper {

private static String separator = "\n";

public ToStringHelper(String seperator) { super(); ToStringHelper.separator = seperator;

}

public static String toString(List l) { StringBuilder sb = new StringBuilder(); String sep = ""; for (Object object : l) { String v = ToStringBuilder.reflectionToString(object); int start = v.indexOf("["); int end = v.indexOf("]"); String st = v.substring(start,end+1); sb.append(sep).append(st); sep = separator; } return sb.toString(); }

public static String toString(Map<?,?> m) {
    StringBuilder sb = new StringBuilder();
    String sep = "";
    for (Object object : m.keySet()) {
      String v = ToStringBuilder.reflectionToString(m.get(object));
      int start = v.indexOf("[");
      int end = v.indexOf("]");
      String st =  v.substring(start,end+1);
        sb.append(sep).append(st);
        sep = separator;
    }
    return sb.toString();
}

public static String toString(Set<?> s) {
    StringBuilder sb = new StringBuilder();
    String sep = "";
    for (Object object : s) {
      String v = ToStringBuilder.reflectionToString(object);
      int start = v.indexOf("[");
      int end = v.indexOf("]");
      String st =  v.substring(start,end+1);
      sb.append(sep).append(st);
      sep = separator;
    }
    return sb.toString();
}

public static void print(List<?> l) {
    System.out.println(toString(l));    
}
public static void print(Map<?,?> m) {
    System.out.println(toString(m));    
}
public static void print(Set<?> s) {
    System.out.println(toString(s));    
}

}

Shekhar