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
Use toArray()
to print the stack values
public void printStack(Stack<Integer> stack) {
// Method 1:
String values = Arrays.toString(stack.toArray());
System.out.println(values);
// Method 2:
Object[] vals = stack.toArray();
for (Object obj : vals) {
System.out.println(obj);
}
}
Throwing a suggestion into the pool here. Depending on your Stack implementation this may or may not be possible.
The suggestion is an anonymous inner class for overriding the toString() in this particular case. This is one way to locally implement the subclassing Marko is mentioning. Your Stack instantiation would look something like
Stack s = new Stack(){
public String toString(){
// query the elements of the stack, build a string and
return nicelyFormattedString;
}
};
...