Printing Java Collections Nicely (toString Doesn't Return Pretty Output)

Elazar Leibovich picture Elazar Leibovich · Dec 27, 2008 · Viewed 194.4k times · Source

I wish to print a Stack<Integer> object as nicely as the Eclipse debugger does (i.e. [1,2,3...]) but printing it with out = "output:" + stack doesn't return this nice result.

Just to clarify, I'm talking about Java's built-in collection so I can't override its toString().

How can I get a nice printable version of the stack?

Answer

Zach Langley picture Zach Langley · Dec 27, 2008

You could convert it to an array and then print that out with Arrays.toString(Object[]):

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