Write a Java Program to Convert a List to Array and Vice Versa

In Java, there are often situations where we need to convert a List to an array or an array to a List.

This can be easily achieved with the help of built-in methods provided by the Java API.


Converting a List to an Array

To convert a List to an array, we can use the toArray() method provided by the List interface.

The toArray() method returns an array containing all the elements in the list.

Here’s an example of how to convert a List of strings to an array of strings:

javascriptCopy codeList<String> list = new ArrayList<>();
list.add("Java");
list.add("Python");
list.add("C++");

String[] array = list.toArray(new String[list.size()]);

In this example, we first create a List of strings and add some elements to it.

We then use the toArray() method to convert the List to an array of strings.

We pass a new String array with the size of the list as an argument to the toArray() method.

This ensures that the returned array has the same size as the list.

Converting an Array to a List

To convert an array to a List, we can use the asList() method provided by the Arrays class.

The asList() method returns a fixed-size List backed by the specified array.

Here’s an example of how to convert an array of integers to a List of integers:

sqlCopy codeint[] array = { 1, 2, 3, 4, 5 };
List<Integer> list = Arrays.asList(array);

In this example, we first create an array of integers and assign some values to it.

We then use the asList() method to convert the array to a List of integers.

Note that the List returned by the asList() method is a fixed-size List, which means that we cannot add or remove elements from it.

If we want to modify the List, we should create a new List and copy the elements from the array to it.


Conclusion

In conclusion, converting a List to an array or an array to a List is a common task in Java programming, and it can be easily accomplished with the help of built-in methods provided by the Java API.