我希望打印一个Stack<Integer>对象,就像Eclipse调试器做的那样(即[1,2,3…]),但打印它与out = "output:" + Stack不会返回这个好结果。
澄清一下,我说的是Java的内置集合,所以我不能重写它的toString()。
我怎样才能得到一个漂亮的可打印版本的堆栈?
我希望打印一个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(' ');
}
}
其他回答
你可以把它转换成一个数组,然后用Arrays.toString(Object[])打印出来:
System.out.println(Arrays.toString(stack.toArray()));
番石榴看起来是个不错的选择:
Iterables.toString (myIterable)
应该适用于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();
}
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);
}
如果这是您自己的集合类,而不是内置的集合类,则需要重写其toString方法。Eclipse对没有固定格式的任何对象调用该函数。