Arraylist is a part of collection framework in java. It contains several inbuilt function like toArray() method which can be found in the java.util.ArrayList Package. It implements the List interface of the collections framework.
Java ArrayList toArray() Method :
The toArray() Returns an array with all the elements in ArrayList in the right order using the ArrayList’s toArray() method.
Syntax :
public Object[] toArray()
or
public T[] toArray(T[] a)
Parameters :
a – the array into which the elements of the list are to be stored, if it is big enough; otherwise, a new array of the same runtime type is allocated for this purpose.
Throws 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
import java.util.*;
public class Main{
public static void main(String[] args) {
//ArrayList object creation .
ArrayList<String> list = new ArrayList<>();
//Adding elements to the list
list.add("A");
list.add("B");
list.add("C");
list.add("D");
list.add("E");
list.add("F");
//Printing the list
System.out.println("ArrayList : " +list);
//converting ArrayList to Array
String[] array = list.toArray(new String[0]);
//Printing the Array
System.out.println("Element of Arraylist as Array :" +Arrays.toString(array));
}
}
Output :
ArrayList : [A, B, C, D, E, F]
Element of Arraylist as Array :[A, B, C, D, E, F]
Explanation :We started by making an arrayList, and then we added the element to it. The output is now printed after the ArrayList has been converted to an Array.
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Login/Signup to comment