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

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

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


当前回答

番石榴看起来是个不错的选择:

Iterables.toString (myIterable)

其他回答

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

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

番石榴看起来是个不错的选择:

Iterables.toString (myIterable)

有两种方法可以简化工作。 1. 导入Gson库。 2. 使用Lombok。

它们都可以帮助您从对象实例创建String。Gson将解析你的对象,lombok将覆盖你的类对象toString方法。

我放了一个关于Gson prettyPrint的例子,我创建了一个helper类来打印对象和对象的集合。如果使用lombok,可以将类标记为@ToString并直接打印对象。

@Scope(value = "prototype")
@Component
public class DebugPrint<T> {
   public String PrettyPrint(T obj){
      Gson gson = new GsonBuilder().setPrettyPrinting().create();
      return gson.toJson(obj);
   }
   public String PrettyPrint(Collection<T> list){
      Gson gson = new GsonBuilder().setPrettyPrinting().create();
      return list.stream().map(gson::toJson).collect(Collectors.joining(","));
   }

}

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);
}

使用java 8流和收集器可以轻松完成:

String format(Collection<?> c) {
  String s = c.stream().map(Object::toString).collect(Collectors.joining(","));
  return String.format("[%s]", s);
}

首先,我们使用map和Object::toString来创建Collection<String>,然后使用join collector来连接Collection中的每个项,作为分隔符。