我希望打印一个Stack<Integer>对象,就像Eclipse调试器做的那样(即[1,2,3…]),但打印它与out = "output:" + Stack不会返回这个好结果。
澄清一下,我说的是Java的内置集合,所以我不能重写它的toString()。
我怎样才能得到一个漂亮的可打印版本的堆栈?
我希望打印一个Stack<Integer>对象,就像Eclipse调试器做的那样(即[1,2,3…]),但打印它与out = "output:" + Stack不会返回这个好结果。
澄清一下,我说的是Java的内置集合,所以我不能重写它的toString()。
我怎样才能得到一个漂亮的可打印版本的堆栈?
当前回答
由Apache Commons项目提供的MapUtils类提供了一个MapUtils. debugprint方法,它将漂亮地打印你的地图。
其他回答
更新的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(' ');
}
}
在类上实现toString()。
我推荐使用Apache Commons ToStringBuilder来简化这个过程。使用它,你只需要写这样的方法:
public String toString() {
return new ToStringBuilder(this).
append("name", name).
append("age", age).
toString();
}
为了得到这样的输出:
Person@7f54 [name =斯蒂芬,age = 29]
还有一个反射实现。
如果这是您自己的集合类,而不是内置的集合类,则需要重写其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中的每个项,作为分隔符。
你可以使用JAVA中的“Objects”类(从1.7开始就有了)
Collection<String> myCollection = Arrays.asList("1273","123","876","897");
Objects.toString(myCollection);
输出:1273,123,876,897
另一种可能是使用谷歌Guave中的"MoreObjects"类,它提供了许多有用的帮助函数:
MoreObjects.toStringHelper(this).add("NameOfYourObject", myCollection).toString());
输出: yourobject =[1273, 123,876, 897]
番石榴文档