Javatpoint Logo
Javatpoint Logo

Java Collection toArray() Method

The toArray() method of Collection Interface returns an array containing all the elements present in the collection.

The second syntax returns an array containing all of the elements in this collection where the runtime type of the returned array is that of the specified array.




The parameter 'a' represents the array in which the elements of the queue will be stored.

Return Value

The toArray() method returns an array that contains all the elements of this queue.


The toArray() method throws:

ArrayStoreException- If the runtime type of the specified array is not a supertype of the runtime type of every element in this collection.

NullPointerException- If the defined array is null.

Example 1

Test it Now


Values :
Element  1: A
Element  2: B
Element  3: C
Element  4: D
Element  5: E
Element  6: F
Element  7: G
Element  8: H
Element  9: I
Element  10: J
Element  11: K
Element  12: L
Element  13: M
Element  14: N
Element  15: O
Element  16: P
Element  17: Q
Element  18: R
Element  19: S
Element  20: T
Element  21: U
Element  22: V
Element  23: W
Element  24: X
Element  25: Y
Element  26: Z

Example 2

Test it Now


Error:(15, 18) java: bad operand types for binary operator '%'
first type:  java.lang.Object
second type: int

Operator '%' cannot be applied to java.lang.Object. If done so, it will give you an error.

Example 3

This example is the solution of the above-described program.

Test it Now


List of even numbers in our collection.

Example 4

Test it Now


Exception in thread "main" java.lang.NullPointerException
	at java.util.concurrent.ConcurrentLinkedQueue.toArray(
	at com.javaTpoint.JavaCollectionToArrayExample4.main(
Next TopicJava Collection

Youtube For Videos Join Our Youtube Channel: Join Now


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Trending Technologies

B.Tech / MCA