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

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

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


当前回答

在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 + ",");
    }
);

其他回答

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

Iterables.toString (myIterable)

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

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

应该适用于Map之外的任何集合,但也很容易支持。 如果需要,修改代码以将这3个字符作为参数传递。

static <T> String seqToString(Iterable<T> items) {
    StringBuilder sb = new StringBuilder();
    sb.append('[');
    boolean needSeparator = false;
    for (T x : items) {
        if (needSeparator)
            sb.append(' ');
        sb.append(x.toString());
        needSeparator = true;
    }
    sb.append(']');
    return sb.toString();
}

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

使用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中的每个项,作为分隔符。