What is the ArrayBlockingQueue.toString method in Java?
ArrayBlockingQueueis a bounded, thread-safe queue that uses a fixed-size array. This means that once the object is created, the size cannot be changed. The elements of this queue follow. First-In-First-Out Elements are inserted at the end of the queue and retrieved from the head of the queue nullobjects are not allowed as elements.
The toString method can be used to get a String representation of the ArrayBlockingQueue object.
Syntax
public String toString()
Parameters
This method doesn’t take any parameters.
Return value
The toString method returns the String representation of the queue object.
-
The elements are enclosed within square brackets
[]. -
Each element is separated by a comma
,. -
Each element is converted to a string with the
String.valueOf(Object)method. -
The elements of the queue are in the order as returned by the iterator.
Code
The code below demonstrates how to use the toString method.
import java.util.concurrent.ArrayBlockingQueue;class ToString {public static void main( String args[] ) {ArrayBlockingQueue<String> queue = new ArrayBlockingQueue<>(5);queue.add("1");queue.add("2");queue.add("3");System.out.println(queue.toString());}}
Explanation
In the code above:
-
In line 1, import
ArrayBlockingQueuefrom thejava.util.concurrentpackage. -
In line 4, create an object for the
ArrayBlockingQueueclass with the namequeueand size 5. -
In lines 5 to 6, use the
addmethod to add three elements to thequeueobject. -
In line 8, use the
toStringmethod to get the string representation of thequeueobject.