Home » Java Collection toArray() Method with Examples

Java Collection toArray() Method with Examples

by Online Tutorials Library

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.

Syntax

Parameters

NA

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.

Throws

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

Output:

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

Output:

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

Output:

List of even numbers in our collection.  2   4   6   8   10  

Example 4

Test it Now

Output:

Exception in thread "main" java.lang.NullPointerException  at java.util.concurrent.ConcurrentLinkedQueue.toArray(ConcurrentLinkedQueue.java:638)  at com.tutorAspire.JavaCollectionToArrayExample4.main(JavaCollectionToArrayExample4.java:12)  
Next TopicJava Collection

You may also like