Convert ArrayList to Array in Java

To convert an ArrayList to an array in Java, you can use the toArray() method of the ArrayList class. Here’s an example:

import java.util.ArrayList;

public class ArrayListToArrayExample {
public static void main(String[] args) {
ArrayList arrayList = new ArrayList();
arrayList.add(1);
arrayList.add(2);
arrayList.add(3);
// Converting ArrayList to Array
    Integer[] array = arrayList.toArray(new Integer[arrayList.size()]);

    // Printing Array
    for (int i = 0; i < array.length; i++) {
        System.out.print(array[i] + " ");
    }
}
}


In this example, we first create an ArrayList of Integer type and add some elements to it. Then, we convert the ArrayList to an array using the toArray() method and store the result in an Integer array. Finally, we print the contents of the array. Note that the toArray() method takes an array of the desired type as an argument, and returns an array of the same type containing the elements of the ArrayList.