1. Introduction
ArrayList and Arrays are two of the most used data structures in Java. There are scenarios where we need to convert an ArrayList to an array, for example, when we need to perform operations that are only applicable to arrays. In this post, we will demonstrate how to convert an ArrayList to an array in Java.
2. Program Steps
1. Initialize an ArrayList with elements.
2. Define an array of suitable size.
3. Use the toArray() method to convert the ArrayList to an array.
3. Code Program
import java.util.ArrayList;
public class ArrayListToArray {
public static void main(String[] args) {
// Step 1: Initialize an ArrayList with elements
ArrayList<String> arrayList = new ArrayList<>();
arrayList.add("Java");
arrayList.add("Python");
arrayList.add("C++");
arrayList.add("JavaScript");
// Step 2: Define an array of suitable size
String[] array = new String[arrayList.size()];
// Step 3: Use the toArray() method to convert the ArrayList to an array
array = arrayList.toArray(array);
// Printing the array
for (String str : array) {
System.out.print(str + " ");
}
}
}
Output:
Java Python C++ JavaScript
4. Step By Step Explanation
In Step 1, we initialize an ArrayList arrayList and add several String elements to it.
In Step 2, we define a String array array whose size is the same as the size of the ArrayList. This is done using arrayList.size() to ensure that the array can hold all the elements of the ArrayList.
In Step 3, we use the toArray() method of the ArrayList class to convert arrayList into an array. We pass the array defined in the previous step to this method, which will be filled with the elements of the ArrayList.
Finally, we print out the elements of the array, and it will contain all the elements from the original ArrayList.