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.
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.
But the ArrayList object it points to is mutable — elements can be changed within it — and declaring list as final has no effect on that.
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.
And if you are using google collection API's (Guava):
Lists.newArrayList(myArray);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With