List中remove元素的理解

今天写了个简单的list中remove元素的方法,结果报错。。。

List<String> ll = Arrays.asList("1","2","3","4","5");
for (int i=0; i < ll.size(); i++){
    ll.remove(i);
}

报错,java.lang.UnsupportedOperationException,这个是因为Arrays.asList()返回AbstractList,没有实现增删改操作,用如下构造方式解决。

List<String> list = new ArrayList<>(Arrays.asList("1","2","3","4","5"));
for (int i = 0; i < list.size(); i++){
    list.remove(i);
}
System.out.println(list);

注意这种方式并不是把所有元素删除(list.size())

list = new ArrayList<>(Arrays.asList("1","2","3","4","5"));
for (String s : list){
    list.remove(s);
}
System.out.println(list);

报错,java.util.ConcurrentModificationException,这个是因为for-each迭代过程中掺杂了修改元素的动作。

 

posted on 2019-01-16 15:59  -赶鸭子上架-  阅读(5830)  评论(0编辑  收藏  举报