1. Introduction
Converting an ArrayList to an array is a common task in Java. It’s particularly handy when we have a list of elements that we need to manipulate as an array, either for performance reasons or to work with legacy code that expects an array as input. Java offers a neat method, toArray(), that can be utilized for this purpose.
2. Program Steps
1. Initialize an ArrayList.
2. Use the toArray() method to convert the ArrayList to an array.
3. Print the array elements.
3. Code Program
import java.util.ArrayList;
import java.util.Arrays;
public class ArrayListToArray {
public static void main(String[] args) {
// 1. Initialize an ArrayList
ArrayList<String> fruitList = new ArrayList<>();
fruitList.add("Apple");
fruitList.add("Banana");
fruitList.add("Cherry");
// 2. Convert the ArrayList to an Array using toArray() method
String[] fruitArray = fruitList.toArray(new String[0]);
// 3. Print the array elements
System.out.println(Arrays.toString(fruitArray));
}
}
Output:
[Apple, Banana, Cherry]
4. Step By Step Explanation
Step 1: An ArrayList of strings, named fruitList, is initialized and populated with fruit names.
Step 2: The toArray() method is used to convert fruitList into an array, fruitArray. The toArray() method requires an argument, which is an 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. Passing an empty array of the correct type is often used for convenience.
Step 3: The elements of the resulting fruitArray are printed to the console using the Arrays.toString() method.