Java ArrayList toArray() Method


What is ArrayList in Java ?

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()
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.

Array list toArray() Method

Return value:

An array containing the elements of the list

Example 1 :  


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

        //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]

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription