本文为转载而来,转载自:https://blog.csdn.net/鲤鱼百合/article/details/60955299
public class ListTest { public static void main(String[] args) { List<Integer> list = new ArrayList<Integer>(); list.add(1); list.add(2); list.add(3); list.add(3); list.add(4); for (int i=0; i<list.size(); i++) { if (list.get(i) == 3) { list.remove(i); } } System.out.println(list); }}
输出结果:[1, 2, 3, 4]
List中元素没有全部删除,由于每remove掉一个元素以后,后面的元素都会向前移动,导致则刚刚移过来的元素没有被读取。所以通过从后向前遍历可以解决这个问题,代码如下:
也可以通过removeAll方法删除,传参是Collection
List<Integer> item = new ArrayList<Integer>();item.add(3);list.removeAll(item);