我希望打印一个Stack<Integer>对象,就像Eclipse调试器做的那样(即[1,2,3…]),但打印它与out = "output:" + Stack不会返回这个好结果。
澄清一下,我说的是Java的内置集合,所以我不能重写它的toString()。
我怎样才能得到一个漂亮的可打印版本的堆栈?
我希望打印一个Stack<Integer>对象,就像Eclipse调试器做的那样(即[1,2,3…]),但打印它与out = "output:" + Stack不会返回这个好结果。
澄清一下,我说的是Java的内置集合,所以我不能重写它的toString()。
我怎样才能得到一个漂亮的可打印版本的堆栈?
当前回答
在类上实现toString()。
我推荐使用Apache Commons ToStringBuilder来简化这个过程。使用它,你只需要写这样的方法:
public String toString() {
return new ToStringBuilder(this).
append("name", name).
append("age", age).
toString();
}
为了得到这样的输出:
Person@7f54 [name =斯蒂芬,age = 29]
还有一个反射实现。
其他回答
你可以试试
org.apache.commons.lang3.builder.ToStringBuilder.reflectionToString(yourCollection);
在类上实现toString()。
我推荐使用Apache Commons ToStringBuilder来简化这个过程。使用它,你只需要写这样的方法:
public String toString() {
return new ToStringBuilder(this).
append("name", name).
append("age", age).
toString();
}
为了得到这样的输出:
Person@7f54 [name =斯蒂芬,age = 29]
还有一个反射实现。
在Collection上调用Sop时要小心,它会抛出ConcurrentModification Exception。因为每个集合的内部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 + ",");
}
);
String.join(",", yourIterable);
(Java 8)