Java program to convert a list to array and vice versa
Here is a Java program to convert a List
to an array and vice versa:
import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class ConvertListToArrayAndArrayToList { public static void main(String[] args) { // Convert List to array List<String> stringList = new ArrayList<>(Arrays.asList("one", "two", "three")); String[] stringArray = stringList.toArray(new String[stringList.size()]); System.out.println("List as array: " + Arrays.toString(stringArray)); // Convert array to List List<String> newStringList = Arrays.asList(stringArray); System.out.println("Array as list: " + newStringList); } }
This program first creates a List
object, stringList
, containing some strings. It then converts the list to an array using the List.toArray()
method. The List.toArray()
method takes an array of the desired type and size as a parameter, and returns an array containing the elements of the list.
Next, the program converts the array back to a list using the Arrays.asList()
method. The Arrays.asList()
method creates a new list containing the elements of the specified array.
Note that the resulting list from the Arrays.asList()
method is not resizable, meaning that you cannot add or remove elements from it. If you need a resizable list, you can create a new ArrayList
object and pass the array to its constructor, like this:
List<String> newStringList = new ArrayList<>(Arrays.asList(stringArray));
This will create a new ArrayList
object that contains the elements of the specified array, and which can be resized using the add()
and remove()
methods.