My intention is to make a shallow clone of the ArrayList
but before that i am facing an issue while modifying the list.
Adding the another element in the list giving
UnsupportedOrderException
WHY?
class Mine implements Cloneable {
public List<Integer> list;
Mine(List<Integer> mylist) {
this.list = mylist;
}
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
class Demo {
public static void main(String[] args) throws CloneNotSupportedException {
List<Integer> klist= Arrays.asList(10,20,30,40,50);
Mine m1=new Mine(klist);
m1.list.add(11); // <- why i am unable to add to the list
Mine m2= (Mine) m1.clone();
}
}
CodePudding user response:
You cannot change the number of elements of the List
(using add()
or remove()
or similar) returned by Arrays.asList
(but it allows to change elements using .set()
).
From the docs of Arrays.asList
:
The returned list implements the optional Collection methods, except those that would change the size of the returned list. Those methods leave the list unchanged and throw UnsupportedOperationException.
Instead, you can create an ArrayList
with the same elements:
List<Integer> klist= new ArrayList<>(Arrays.asList(10,20,30,40,50));
CodePudding user response:
Arrays.asList()
returns a List<T>
implementation that is backed by the original array. (Changed to the array can be seen via the list and vice versa.)
Arrays have a fixed size in Java, therefore the list returned by Arrays.asList
has to have a fixed size as well - you can't add to it, and you can't remove from it.
You can create a new ArrayList<T>
instead, which creates a copy of the array:
List<Integer> list = new ArrayList<>(Arrays.asList(...));
Although ArrayList
is still backed by an array, it will create a new array where necessary. The array is an implementation detail, rather than the list being a "view" over an existing array as is returned by Arrays.asList
.
CodePudding user response:
In addition to @dan1st's answer (and now @JonSkeet as well), you can create your own asList()
method to return a mutable List<T>
:
static public List<T> asMutableList(T ... elts) {
List<T> lst = new ArrayList<>(elts.length);
for (T el : elts) {
lst.add(el);
}
return lst;
}