Array backed list

In this tutorial we will examine what is array backed list and how it behave.

Creation

Array backed lists are lists, which were constructed directly from arrays:

String[] array = {"cat", "dog", "canary"}
List<String> list = Arrays.asList(array);

or

List<String> list = Arrays.asList("cat", "dog", "canary");

As a consequence of calling java.util.Arrays.asList(), the list is backed by an array. It means that the list points to the same data structure in heap, as the array.

Modification
Any modification through list reference will be visible via the array instance also – the same happens in the opposite direction.

Let’s check this by code:

String[] array = {"mouse", "cat", "canary"};
List list = Arrays.asList(array);
System.out.println("array: " + Arrays.toString(array));
System.out.println("list: " + list);

list.set(0, "cat");
System.out.println("nafter replacing first element in the list:");
System.out.println("array: " + Arrays.toString(array));
System.out.println("list: " + list);

array[1] = "dog";
System.out.println("nafter replacing second element in the array:");
System.out.println("array: " + Arrays.toString(array));
System.out.println("list: " + list);

the output should be:

array: [mouse, cat, canary]
list: [mouse, cat, canary]

after replacing first element in the list:
array: [cat, cat, canary]
list: [cat, cat, canary]

after replacing second element in the array:
array: [cat, dog, canary]
list: [cat, dog, canary]

We see that modification on specific element in any of the reference reflects changes in both of them.

Limitations

Lists backed by an arrays are fixed-length – we cannot add or remove elements. Any attempt of changing size:

list.add("cat");
list.remove(0);

will result with the following exception

java.lang.UnsupportedOperationException
 at java.util.AbstractList.add(AbstractList.java:148)
 at java.util.AbstractList.add(AbstractList.java:108)
 at com.pwc.ocp.ListTester.main(ListTester.java:27)

When we check the class returned by the Arrays.asList(), we will get:

class java.util.Arrays$ArrayList

At first glance we see that it is ArrayList, but be careful – after a thorough look we see, that this is a nested class inside the java.util.Arrays class. This nested class provides its own implementation of List, that propagate changes to the array and doesn’t allow any calls of add*() or remove*() methods.

Leave a Reply

Your email address will not be published. Required fields are marked *