Printing the stack values in Java

后端 未结 8 1554
小蘑菇
小蘑菇 2021-01-11 12:40

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

相关标签:
8条回答
  • 2021-01-11 13:31

    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);
        }
    }
    
    0 讨论(0)
  • 2021-01-11 13:31

    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;
                  }
              };
    ...
    
    0 讨论(0)
提交回复
热议问题