Bits of Java – Episode 13: From Arrays to Lists and vice versa

In this episode I would like to discuss how to pass from an array to a list and vice versa, and which are the things to keep in mind once the conversion has been done.

  • From *list* to *array*: to pass from a list to an array you can simply use the toArray() method:

List<Integer> list = new ArrayList<Integer>();

Object[] array = list.toArray();
Integer[] array2 = list.toArray(new Integer[0]);

If you call toArray() without any parameter, you create an array of Object. To get the right type, you need to pass it as parameter (in our case we wanted an array of Integer, so we passed new Integer[0]). Specifying the size as 0 means that you want Java to take care of the actual size and create the right dimension for your array. It is possible also to specify another number; in that case Java will create an array of the specified size if it fits the list you want to convert, otherwise it will create another one.

From *array* to *list*: to pass, instead, from array to list you have two main possibilities: Arrays.asList() and List.of(). The result, in both case, is a List with fixed size, meaning that every operation that would modify the size of the list is not allowed, and will throw an Exception at runtime.

String[] array = {"a", "b", "c"};
List<String> list = Arrays.asList(array);

List<String> list2 = List.of(array);

The difference between the two methods is that Arrays.asList allows the list to change values (just values, not size, remember!) and changing the values in the list modifies also the original array, as well as the opposite. While, List.of() create a really immutable list, meaning that not only the size cannot be changed, but neither the values!

String[] array = {"a", "b", "c"};
List<String> list = Arrays.asList(array);
list.set(2, "d"); //ALLOWED, both array and list contain now "a", "b", "d"

List<String> list2 = List.of(array);

So, remember that passing from an array to a list and vice versa is possible, but, while from list to array is pretty straightforward, the opposite direction is not so obvious, since the resulting list cannot be changed in size, and, depending on the method you use for the conversion, you will have to keep in mind that changes on the list can affect the original array, as well as the opposite, or that the resulting list is an immutable one so neither changes in the values are allowed. These features are tricky because at compiling time you will not get any notification of that, but, at runtime, an Exception will be thrown!

Stay tuned for the next episode of the series: the static keyword!

by Ilenia Salvadori