1. Introduction
In Java, Arrays and ArrayLists are both used to store data, but they differ in their properties and operations. An array is a fixed-size data structure while ArrayList is dynamic. Converting an array to an ArrayList can be useful when dealing with a varying number of elements. In this post, we will explore how to convert an Array to ArrayList in Java.
2. Program Steps
1. Initialize an array with elements.
2. Use the Arrays.asList() method to convert the array to a List.
3. Initialize an ArrayList using the List obtained from the previous step.
3. Code Program
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ArrayToArrayList {
public static void main(String[] args) {
// Step 1: Initialize an array with elements
String[] array = {"Java", "Python", "C++", "JavaScript"};
// Step 2: Use the Arrays.asList() method to convert the array to a List
List<String> list = Arrays.asList(array);
// Step 3: Initialize an ArrayList using the List obtained from the previous step
ArrayList<String> arrayList = new ArrayList<>(list);
// Printing the ArrayList
System.out.println(arrayList);
}
}
Output:
[Java, Python, C++, JavaScript]
4. Step By Step Explanation
In Step 1, we initialize an array array containing several String elements.
During Step 2, we utilize the Arrays.asList() method, which converts the array into a List. This method returns a fixed-size list backed by the specified array.
In Step 3, we initialize an ArrayList arrayList by passing the List obtained in the previous step to the ArrayList constructor. This step is crucial as the List returned by Arrays.asList() is fixed-size, and if we want to perform add or remove operations, we must convert it to an ArrayList.
Finally, we print out the arrayList, and it will contain all the elements from the original array.