我希望打印一个Stack<Integer>对象,就像Eclipse调试器做的那样(即[1,2,3…]),但打印它与out = "output:" + Stack不会返回这个好结果。

澄清一下,我说的是Java的内置集合,所以我不能重写它的toString()。

我怎样才能得到一个漂亮的可打印版本的堆栈?


当前回答

你可以试试

org.apache.commons.lang3.builder.ToStringBuilder.reflectionToString(yourCollection);

其他回答

你可以把它转换成一个数组,然后用Arrays.toString(Object[])打印出来:

System.out.println(Arrays.toString(stack.toArray()));

由Apache Commons项目提供的MapUtils类提供了一个MapUtils. debugprint方法,它将漂亮地打印你的地图。

system . out。println(集合c)已经以可读格式打印任何类型的集合。只有当集合包含用户定义的对象时,才需要在用户定义的类中实现toString()来显示内容。

如果这是您自己的集合类,而不是内置的集合类,则需要重写其toString方法。Eclipse对没有固定格式的任何对象调用该函数。

JSON

另一种解决方案是将您的集合转换为JSON格式并打印JSON - string。其优点是格式良好且可读的Object-String,而不需要实现toString()。

使用谷歌的Gson的示例:

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

...

    printJsonString(stack);

...
public static void printJsonString(Object o) {
    GsonBuilder gsonBuilder = new GsonBuilder();
    /*
     * Some options for GsonBuilder like setting dateformat or pretty printing
     */
    Gson gson = gsonBuilder.create();
    String json= gson.toJson(o);
    System.out.println(json);
}