In this example, we will learn to convert a Java list to an array and vice versa.
Example 1: Convert the Java List into Array
import java.util.ArrayList; class Main { public static void main(String[] args) { ArrayList languages = new ArrayList<>(); // Add elements in the list languages.add("Java"); languages.add("Python"); languages.add("JavaScript"); System.out.println("ArrayList: " + languages); // Create a new array of String type String[] arr = new String[languages.size()]; // Convert ArrayList into the string array languages.toArray(arr); System.out.print("Array: "); for(String item:arr) { System.out.print(item+", "); } } }
Output
List: [Java, Python, JavaScript] Array: Java, Python, JavaScript,
In the above example, we have created an list named languages. Here, we have used the ArrayList
class to implement the List
.
Notice the line,
languages.toArray(arr);
Here, the toArray()
method converts the list languages into an array. And stores it in the string array arr.
Note: If we don’t pass any argument to the toArray()
method, the method returns an array of the Object
type.
Example 2: Convert Java Array to List
import java.util.Arrays; import java.util.ArrayList; import java.util.List; class Main { public static void main(String[] args) { // create an array String[] array = {"Java", "Python", "C"}; System.out.println("Array: " + Arrays.toString(array)); // convert array to list List languages= new ArrayList<>(Arrays.asList(array)); System.out.println("List: " + languages); } }
Output
Array: [Java, Python, C] List: [Java, Python, C]
In the above example, we have created an array of String
type. Notice the expression,
Arrays.asList(array)
Here, the asList()
method of the Arrays
class converts the specified array into a list.