list remove元素

public class TestList {
    public static void main(String[] args)  {
        List<Integer> list = new LinkedList<Integer>();
        list.add(2);
        list.add(3);
        for (Iterator iterator = list.iterator(); iterator.hasNext();) {
             System.out.println(list);
            Integer integer = (Integer) iterator.next();
            iterator.remove();
        }
        System.out.println(list);
    }
}

[2, 3]
[3]
[]

 

错误的写法

for (Integer integer : list) {
              System.out.println(list);
                list.remove(integer);
        }
 System.out.println(list);
 

[2, 3]
[3]

posted @ 2017-10-10 10:35  tonggc1668  阅读(133)  评论(0编辑  收藏  举报