How can I override the
toString()
method ofQueue
class to get the correct output ?
You can't.
For starters, Queue
is not a class, it's an interface. The concrete class you're using is LinkedList
.
More concretely what you could do is defining a custom class that implements Queue
and extends, for example LinkedList
, and that class can have a custom toString
method (see implementation below).
I donot want to get the output by iterating over the queue. I hope to achieve it somehow by overriding the
toString()
method.
You'll have to iterate eventually, one way or another. You can just hide that iteration in another method, but the iteration will still be there under the hood.
Here's a quick blueprint of what you can do
import java.util.Queue;import java.util.LinkedList;import java.util.Arrays;import java.util.stream.Collectors;public class ArrayQueue extends LinkedList<int[]> implements Queue<int[]> { @Override public String toString() { return this.stream() .map(Arrays::toString) .collect(Collectors.joining(", ", "[", "]")); }}
And a test program
import java.util.Queue;public class ArrayQueueTest { public static void main(String args[]) { Queue<int[]> q = new ArrayQueue(); q.add(new int[]{1, 2, 3}); q.add(new int[]{4, 5, 6}); q.add(new int[]{7, 8, 9}); System.out.println(q); }}
Running this yields
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]