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

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

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


当前回答

更新的JDK已经实现了AbstractCollection.toString(),并且Stack扩展了AbstractCollection,所以你只需要在你的集合上调用toString():

    public abstract class AbstractCollection<E> implements Collection<E> {
    ...
    public String toString() {
        Iterator<E> it = iterator();
        if (! it.hasNext())
            return "[]";
    
        StringBuilder sb = new StringBuilder();
        sb.append('[');
        for (;;) {
            E e = it.next();
            sb.append(e == this ? "(this Collection)" : e);
            if (! it.hasNext())
                return sb.append(']').toString();
            sb.append(',').append(' ');
        }
    }

其他回答

在Collection上调用Sop时要小心,它会抛出ConcurrentModification Exception。因为每个集合的内部toString方法在内部调用集合上的迭代器。

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

有两种方法可以简化工作。 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(","));
   }

}

在Java8

//will prints each element line by line
stack.forEach(System.out::println);

or

//to print with commas
stack.forEach(
    (ele) -> {
        System.out.print(ele + ",");
    }
);

更新的JDK已经实现了AbstractCollection.toString(),并且Stack扩展了AbstractCollection,所以你只需要在你的集合上调用toString():

    public abstract class AbstractCollection<E> implements Collection<E> {
    ...
    public String toString() {
        Iterator<E> it = iterator();
        if (! it.hasNext())
            return "[]";
    
        StringBuilder sb = new StringBuilder();
        sb.append('[');
        for (;;) {
            E e = it.next();
            sb.append(e == this ? "(this Collection)" : e);
            if (! it.hasNext())
                return sb.append(']').toString();
            sb.append(',').append(' ');
        }
    }