Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create mutable List from array?

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.

like image 495
ericsoco Avatar asked Jul 25 '12 21:07

ericsoco


People also ask

How do you make an ArrayList mutable?

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.

Is ArrayList mutable in Java?

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.


Video Answer


2 Answers

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.

like image 140
Jon Skeet Avatar answered Sep 19 '22 20:09

Jon Skeet


And if you are using google collection API's (Guava):

Lists.newArrayList(myArray); 
like image 41
vsingh Avatar answered Sep 20 '22 20:09

vsingh