LinkedBlockingQueue toArray() method in Java
The toArray method of LinkedBlockingQueue is used to create an array having the same elements as that of this LinkedBlockingQueue, in proper sequence. Actually, this method copies all the elements from the LinkedBlockingQueue to a new array. This method behaves as a bridge between array and LinkedBlockingQueue.
public Object toArray()
Return Value: This method returns an array that contains the elements of LinkedBlockingQueue.
Below programs illustrates toArray() method of LinkedBlockingQueue class:
Queue Contains [2300, 1322, 8945, 6512] The array contains: 2300 1322 8945 6512
The array contains: User Employee Manager Analyst HR
The toArray(T a) method of LinkedBlockingQueue is used to return an array containing the same elements as that of this LinkedBlockingQueue, in proper sequence. This method differs from toArray() in only one condition. The type of the returned array is the same as the passed array in the parameter if the LinkedBlockingQueue size is less than or equal to the passed array. Otherwise, a new array is allocated with the type same as the specified array, and the size of the array is equal to the size of this queue. This method behaves as a bridge between array and collections.
public <T> T toArray(T a)
Parameter: This method takes an array as parameter into which all of the elements of the queue are to be copied if it is big enough. Otherwise, a new array of the same runtime type is allocated to this.
Return Value: This method returns an array containing all of the elements in this queue.
Exception This method throws the following exceptions:
- ArrayStoreException: When the passed array is of a different type from the type of elements of LinkedBlockingQueue.
- NullPointerException: If the passed array is Null.
Below programs illustrates toArray(T a) method of LinkedBlockingQueue class:
Queue Contains : [Sonali, Sonam, Kajal, Komal] The array passed : Sonali Sonam Kajal Komal The array returned : Sonali Sonam Kajal Komal
Program 2: Passing different type of array in toArray() from the type of element LinkedBlockingQueue contains. The toArray() method will hence throw exception ArrayStoreException.
Exception: java.lang.ArrayStoreException: java.lang.Integer
Program 3: Passing null array in toArray(). Hence toArray() method will throw NullPointerException.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.