【发布时间】:2021-11-24 02:26:15
【问题描述】:
我的意图是对ArrayList 进行浅层克隆,但在此之前我在修改列表时遇到了问题。
在列表中添加另一个元素
UnsupportedOrderException
为什么?
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();
}
}
【问题讨论】:
-
@AritroShome,
List是一个有很多实现的接口,而不仅仅是ArrayList。 -
List是一个接口,它本身没有实现。改用ArrayList<T>,实现List