new ArrayList(Arrays.asList(myArray))
To convert a String array to an ArrayList in Core Java, you can use the Arrays.asList()
method to convert the array to a List and then create an ArrayList from that List. Here’s an example:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class StringArrayToArrayList {public static void main(String[] args) {
// Example String array
String[] stringArray = {“One”, “Two”, “Three”, “Four”, “Five”};
// Convert String array to ArrayListList<String> stringList = Arrays.asList(stringArray);
ArrayList<String> arrayList = new ArrayList<>(stringList);
// Print the ArrayList
System.out.println(“ArrayList: “ + arrayList);
}
}
In this example, Arrays.asList(stringArray)
is used to convert the String array to a List, and then new ArrayList<>(stringList)
is used to create an ArrayList from that List. Note that using Arrays.asList()
directly with ArrayList
constructor may result in an unsupported operation if you try to modify the size of the ArrayList (add or remove elements). Wrapping it with new ArrayList<>(stringList)
ensures that the resulting ArrayList can be modified.