Sure, here’s how you can create an ArrayList from an array in Java:
Java
import java.util.ArrayList;
import java.util.Arrays;
public class ArrayToArrayList {
public static void main(String[] args) {
// Create an array
String[] array = {"apple", "banana", "orange"};
// Convert array to ArrayList
ArrayList<String> arrayList = new ArrayList<>(Arrays.asList(array));
// Print the ArrayList
System.out.println("ArrayList: " + arrayList);
}
}Explanation:
- First, import the required classes: ‘
ArrayList‘ from ‘java.util‘ and ‘Arrays‘. - Create an array of strings ‘
array‘ with some elements. - Use ‘
Arrays.asList(array)‘ to convert the array to a List. - Pass this list as an argument to the ‘
ArrayList‘ constructor, which creates a new ArrayList containing the elements of the list. - Now, you have an ArrayList ‘
arrayList‘ containing the elements of the original array. - Finally, print out the ArrayList to see its contents.
