Search code examples
javaarrayslinked-listqueue

Java - print contents of a queue


I have a queue (where each element is an array of integer) defined as -

Queue<int[]> queue = new LinkedList<>();

When I try to print the queue, I get output like this as it prints the array object -

[[I@58d25a40]

How can I override the toString() method of Queue class to get the correct output ? I donot want to get the output by iterating over the queue. I hope to achieve it somehow by overriding the toString() method.


Solution

  • You can try something like this:

    Queue<int[]> queue = new LinkedList<>() {
      @Override public String toString() {
        return "[" +
          stream()
          .map(Arrays::toString)
          .collect(Collectors.joining(", ")) +
          "]";
      }
    };
    
    queue.add(new int[] {1, 2});
    queue.add(new int[] {3, 4});
    System.out.println(queue);
    

    printing:

    [[1, 2], [3, 4]]
    

    Which is presumably what you want.

    This isn't necessarily a good idea. toString() should be used solely for debugging purposes: toString demands nothing of implementations, not even that they are consistent. Most things I can think of that would lead one to ask this question are problematic.