Java Collection toArray() MethodThe 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 1Test it NowOutput: 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 2Test it NowOutput: 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. Test it NowOutput: List of even numbers in our collection. 2 4 6 8 10 Example 4Test it NowOutput: Exception in thread "main" java.lang.NullPointerException at java.util.concurrent.ConcurrentLinkedQueue.toArray(ConcurrentLinkedQueue.java:638) at com.javaTpoint.JavaCollectionToArrayExample4.main(JavaCollectionToArrayExample4.java:12) Next TopicJava Collection |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India