码迷,mamicode.com
首页 > 其他好文 > 详细

arraylist 为什么 删除元素时要使用迭代器而不能使用遍历

时间:2018-12-06 14:23:44      阅读:320      评论:0      收藏:0      [点我收藏+]

标签:ber   string   static   index   val   comm   plain   arraylist   lin   

因为你要是遍历了,arraylist 的长度就变了,容易数组越界和下标问题

 

public class Test {

    public static void main(String[] args)  {
        ArrayList<Integer> list = new ArrayList<Integer>();
        list.add(2);
        Iterator<Integer> iterator = list.iterator();
        while(iterator.hasNext()){
            Integer integer = iterator.next();
            if(integer==2)
                iterator.remove();   //注意这个地方
        }
    }
}

arraylist 为什么 删除元素时要使用迭代器而不能使用遍历

标签:ber   string   static   index   val   comm   plain   arraylist   lin   

原文地址:https://www.cnblogs.com/shenzhichipingguo/p/10075785.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!