ericsoco ericsoco - 1 year ago 99
Java Question

Create mutable List from array?

I have an array I'd like to turn into a

, in order to modify the contents of the array.

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

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
each value into a new List, but I'm wondering if there's an interface that exists to do this for me.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download