1. Introduction
In Java, we often find ourselves needing to convert a List to an Array. The List interface provides flexibility and ease of manipulation, whereas an Array is more efficient in terms of memory. The conversion from a List to an Array can be easily achieved using the toArray() method provided by the List interface. In this post, we will demonstrate how to perform this conversion.
2. Program Steps
1. Initialize a List with some elements.
2. Convert the List to an Array using the toArray() method.
3. Print the original List and the converted Array.
3. Code Program
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
public class ListToArray {
public static void main(String[] args) {
// Step 1: Initialize a List with some elements
List<String> fruitList = new ArrayList<>();
fruitList.add("Apple");
fruitList.add("Banana");
fruitList.add("Cherry");
// Step 2: Convert the List to an Array using the toArray() method
String[] fruitArray = fruitList.toArray(new String[0]);
// Step 3: Print the original List and the converted Array
System.out.println("Original List: " + fruitList);
System.out.println("Converted Array: " + Arrays.toString(fruitArray));
}
}
Output:
Original List: [Apple, Banana, Cherry] Converted Array: [Apple, Banana, Cherry]
4. Step By Step Explanation
Step 1: We create a List named fruitList and add some elements to it.
Step 2: We call the toArray() method on the fruitList to convert it to an Array. The toArray() method takes as a parameter an array which will be filled with the list elements. If this array is too small, a new array of the same runtime type is allocated with the size of the list. In our case, we pass an empty array of type String, so a new array is allocated with the size of the fruitList.
Step 3: Lastly, we print the original fruitList and the fruitArray to the console. We use Arrays.toString() method to print the array elements, as arrays don’t override the toString() method from the Object class.