How to make array backed list editable

Suppose we have a list that is backed by an array. In another words – that we have a wrapper around the array. Our question is: how to add or remove elements from that list?

The answer is: We can’t (see array-backed-list for details). But we can create a new List based on the previous one, for example:

List modifiableList = new ArrayList(Arrays.asList(list));

The above code will create modifiable list with any fixed-length constraints. From now you can add or remove elements to modifiableList.
Please be aware that after running this code, you will also loose relation to the backing array – any changes made to modifiableList won’t be reflected in the array – that’s because constructor of the list makes a copy of all references in source list.

Leave a Reply

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