In Java, there are these array-backed
lists that are generated when you convert arrays to lists using Arrays.asList(...)
. The list and the array objects point to the same data stored in the heap. Changes to the existing contents through either the list or array result to changing the same data.
For instance, we have these codes which were taken from Converting Between array and List in Java.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | package arraytolist; import java.util.Arrays; import java.util.List; public class ArrayToListAndBack { public static void main(String[] args) { String[] names = { "Karl", "Peter", "Lucas" }; // Array to list List<String> listNames = Arrays.asList(names); // List to array String[] newArrayNames = listNames.toArray(new String[0]); for (String t : newArrayNames) { System.out.println(t); } } } |
Array to List
Notice this code:
1 | List<String> listNames = Arrays.asList(names); |
It creates an array-backed list. Any change to the current data will be reflected on the original array names
. Let’s modify the codes a bit to show this “phenomena”.
Test the effects
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | package arraytolist; import java.util.Arrays; import java.util.List; public class ArrayToListAndBack { public static void main(String[] args) { String[] names = { "Karl", "Peter", "Lucas" }; // Array to list List<String> listNames = Arrays.asList(names); listNames.set(0, "Karlito"); System.out.println("List contents:" + listNames.toString()); System.out.println("Original array contents: " + Arrays.toString(names)); } } |
On line 13, we changed the value of the first element in the list. Not in the array. However, the original array is also modified.
1 2 | List contents:[Karlito, Peter, Lucas] Original array contents: [Karlito, Peter, Lucas] |
List becomes fixed-length
The array-backed list is fixed-length. You cannot change the list by adding or removing elements.
If you try to, java.lang.UnsupportedOperationException
is thrown.
1 2 3 4 5 6 | ... System.out.println("List contents:" + listNames.toString()); System.out.println("Original array contents: " + Arrays.toString(names)); listNames.add("George"); ... |
Try adding “George” in the list and the codes will output the following.
1 2 3 4 5 6 | List contents:[Karlito, Peter, Lucas] Original array contents: [Karlito, Peter, Lucas] Exception in thread "main" java.lang.UnsupportedOperationException at java.util.AbstractList.add(AbstractList.java:148) at java.util.AbstractList.add(AbstractList.java:108) at arraytolist.ArrayToListAndBack.main(ArrayToListAndBack.java:18) |