1. 用for循环(只能递减遍历)
public static void main(String[] args) { List<String> list = new ArrayList<String>(); list.add("111"); list.add("222"); list.add("333"); list.add("222"); list.add("444"); for (int i = list.size() - 1; i >= 0; i--) { if ("222".equals((String)list.get(i))) { list.remove(i); System.out.println(list.get(i)); } } System.out.println("=========" + list.size()); for (String str : list) { System.out.println(str); } }
运行结果:
222
222
=========3
111
333
444
2. 用迭代器删除元素:
public static void main(String[] args) { List<String> list = new ArrayList<String>(); list.add("111"); list.add("222"); list.add("333"); list.add("222"); list.add("444"); Iterator<String> itr = list.iterator(); while (itr.hasNext()) { String str = itr.next(); if ("333".equals(str)) { itr.remove(); } } for (String str : list) { System.out.println(str); } }
运行结果:
111
222
222
444
时间: 2024-10-10 00:29:12