toArray() Method : Java.util.ArrayList
Declaration :
1 |
public <T> T[] toArray(T[] arr) |
Explanation :
Purpose | Method returns an array having all the elements in this list in sequence. |
Parameters | arr ==> Array into which the elements of the list are to be stored |
Return Value | Array containing the elements of the list |
Exception | ArrayStoreException ==> If the runtime type of the specified array is not a supertype of the runtime type of every element in this list |
NullPointerException ==> If the specified array is null |
Example
The following example shows the usage of java.util.Arraylist.toArray(E) method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
package com.c4learn.arraylist; import java.util.ArrayList; public class ArrayListExamples { public static void main(String args[]) { // Create ArrayList 1 ArrayList<String> arrlist1 = new ArrayList<String>(5); // Fill Elements in ArrayList 1 arrlist1.add("A"); arrlist1.add("B"); arrlist1.add("C"); // Create String Array String arr[] = new String[arrlist1.size()]; arr = arrlist1.toArray(arr); // Print ArrayList for (String str : arr) { System.out.println("List Element : " + str); } } } |
Output :
1 2 3 |
List Element : A List Element : B List Element : C |