Printing the stack values in Java

后端 未结 8 1553
小蘑菇
小蘑菇 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:19

    From documentation of toString() method of AbstractCollection. So you can not do it unless you define your own StackOr 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.

    0 讨论(0)
  • 2021-01-11 13:22

    Try this:

     System.out.println(Arrays.asList(stackobject.toArray()));
     System.out.println(Arrays.toString(stackobject.toArray()));
    
    0 讨论(0)
  • 2021-01-11 13:24

    There is a workaround.

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

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

    0 讨论(0)
  • 2021-01-11 13:24

    Another method is the join method of String which is similar to the join method of Python:

    "" + String.join("/", stack)
    

    This will return the string containing all the elements of the stack and we can also add some delimiter by passing in the first argument.

    Example: Stack has two elements [home, abc]

    Then this will return "/home/abc".

    0 讨论(0)
  • 2021-01-11 13:27

    Use the same kind of loop that you used to fill the stack and print individual elements to your liking. There is no way to change the behavior of toString, except if you go the route of subclassing Stack, which I wouldn't recommend. If the source code of Stack is under your control, then just fix the implementation of toString there.

    0 讨论(0)
  • 2021-01-11 13:30
    stack.forEach(System.out::println);
    

    Using Java 8 and later stream functions

    0 讨论(0)
提交回复
热议问题