import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ListArray {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("a");
list.add("b");
String[] array = new String[list.size()];
list.toArray(array);
System.out.println(Arrays.toString(array));
}
}
When you run the program, the output will be:
[a, b]
In the above program, we've an list of strings list. To convert the list to an array, first we created a string array named array with size equals to list.size()
.
Then, we simply used list's toArray()
method to convert the list items to array items.
import java.util.Arrays;
import java.util.List;
public class ArrayToList {
public static void main(String[] args) {
String[] array = {"a", "b"};
List<String> list = Arrays.asList(array);
System.out.println(list);
}
}
When you run the program, the output will be:
[a, b]
In the above program, we've an array of strings array. To convert the array to a list, we used Arrays
's asList()
method and stored it in the list, list.
It takes a lot of effort and cost to maintain Programiz. We would be grateful if you support us by either:
Disabling AdBlock on Programiz. We do not use intrusive ads.
or
Donate on Paypal