In Java, I want to print the contents of a Stack. The toString()
method prints them encased in square brackets delimited by commas: [foo, bar, ba
From documentation of toString() method of AbstractCollection
. So you can not do it unless you define your own Stack
Or implement custom toString() by iterating over Stack
public String toString()
Returns a string representation of this collection. The string representation consists of a list of the collection's elements in the order they are returned by its iterator, enclosed in square brackets ("[]"). Adjacent elements are separated by the characters ", " (comma and space). Elements are converted to strings as by String.valueOf(Object).
This implementation creates an empty string buffer, appends a left square bracket, and iterates over the collection appending the string representation of each element in turn. After appending each element except the last, the string ", " is appended. Finally a right bracket is appended. A string is obtained from the string buffer, and returned.