Java Collection toArray() MethodLast Updated : 17 Mar 2025 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. SyntaxParametersNA The parameter 'a' represents the array in which the elements of the queue will be stored. Return ValueThe toArray() method returns an array that contains all the elements of this queue. ThrowsThe 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 1Output: 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 2Output: 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 3This example is the solution of the above-described program. Output: List of even numbers in our collection. 2 4 6 8 10 Example 4Output: Exception in thread "main" java.lang.NullPointerException at java.util.concurrent.ConcurrentLinkedQueue.toArray(ConcurrentLinkedQueue.java:638) at com.tpointtech.JavaCollectionToArrayExample4.main(JavaCollectionToArrayExample4.java:12) Next TopicJava Collection |
We request you to subscribe our newsletter for upcoming updates.

We deliver comprehensive tutorials, interview question-answers, MCQs, study materials on leading programming languages and web technologies like Data Science, MEAN/MERN full stack development, Python, Java, C++, C, HTML, React, Angular, PHP and much more to support your learning and career growth.
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India