Java开发笔记之List删除元素foreach删除元素
错误的循环删除
ArrayList<Integer> list = new ArrayList<>(); for (int i = 0; i < 5; i++) { list.add(i); } for (Integer integer : list) { System.out.println(integer); if(integer.equals(3)){ list.remove(integer); } } System.out.println(list);
使用迭代器的正确删除
ArrayList<Integer> list = new ArrayList<>(); for (int i = 0; i < 5; i++) { list.add(i); } Iterator<Integer> iterator = list.iterator(); while(iterator.hasNext()){ System.out.println(iterator.next()); iterator.remove(); } System.out.println(list); }