Create mutable List from array?

ericsoco picture ericsoco · Jul 25, 2012 · Viewed 52.4k times · Source

I have an array I'd like to turn into a List, in order to modify the contents of the array.

Stack Overflow has plenty of questions/answers that address Arrays.asList() and how it only provides a List view of the underlying array, and how attempting to manipulate the resulting List will generally throw an UnsupportedOperationException as methods used to manipulate the list (e.g. add(), remove(), etc.) are not implemented by the List implementation provided by Arrays.asList().

But I can't find an example of how to turn an array into a mutable List. I suppose I can loop through the array and put() each value into a new List, but I'm wondering if there's an interface that exists to do this for me.

Answer

Jon Skeet picture Jon Skeet · Jul 25, 2012

One simple way:

Foo[] array = ...;
List<Foo> list = new ArrayList<Foo>(Arrays.asList(array));

That will create a mutable list - but it will be a copy of the original array. Changing the list will not change the array. You can copy it back later, of course, using toArray.

If you want to create a mutable view onto an array, I believe you'll have to implement that yourself.