How to convert ArrayList to Array in Java?

By Preeti Jain Last updated : February 05, 2024

Problem statement

Given an ArrayList, write a Java program to convert the given ArrayList to an Array.

Converting ArrayList to Array in Java

To convert an ArrayList to an Array, you can use toArray() method.

toArray() Method

  • toArray() method is available in java.util package.
  • toArray() method is used to return a converted Array object which contains all of the elements in the ArrayList.
  • toArray() method does not throw any exception at the time of conversion from ArrayList to Array.
  • It's not a static method, it is accessible with class objects (i.e. If we try to execute with the class name then we will get an error).
  • It's not a final method, it is overridable in child class if we want.

Syntax

public Object[] toArray(){
}

Parameter(s)

It does not accept any parameter.

Return value

The return type of this method is Object[], it returns a converted ArrayList to an Array which contains all of the elements in the ArrayList.

Java program to convert ArrayList to Array

// Java program to demonstrate the example of
// conversion of an ArrayList to an Array with 
// the help of toArray() method of ArrayList

import java.util.*;

public class ArrayListToArray {
    public static void main(String[] args) {
        // ArrayList Declaration
        ArrayList arr_list = new ArrayList();

        // By using add() method to add few elements in 
        // ArrayList

        arr_list.add(10);
        arr_list.add(20);
        arr_list.add(30);
        arr_list.add(40);
        arr_list.add(50);

        // Display ArrayList
        System.out.println("ArrayList elements:");
        System.out.println(arr_list);

        System.out.println();

        // By using toArray() method is used to convert 
        // ArrayList to Array

        Object[] arr = arr_list.toArray();

        // Display Array
        System.out.println("Array elements: ");

        for (Object o: arr)
            System.out.println(o);
    }
}

Output

The output of the above program is:

ArrayList elements:
[10, 20, 30, 40, 50]

Array elements: 
10
20
30
40
50

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.