List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < 10; i++) {
list.add(i);
}
System.out.println(list); //[0, 1,2, 3, 4, 5, 6, 7, 8, 9]
// 直接在List循环中删除元素会抛出ConcurrentModificationException
/*
for (Integer i : list) {
if(i % 4 == 0) {
list.remove(i);
}
}
System.out.println(list.size());
*/
// 可以通过Iterator 删除元素
Iterator iterator = list.iterator();
while (iterator.hasNext()) {
Integer i = iterator.next();
if (i% 4 == 0) {
iterator.remove();
}
}
System.out.println(list); //[1, 2, 3, 5, 6, 7, 9],已经删除4、8
list.remove(3);
System.out.println(list); //[1,2, 3, 6, 7, 9],删除了序号为3个元素 list[3]
list.remove(new Integer(3));
System.out.println(list); //[1,2, 6, 7, 9],删除值为3的元素