删除list中不满足条件的数据
从头遍历list的话每一次删除数据下标对应的数据会发生变化
1.从尾部往前遍历
package intership; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * @Author: yf.zuo * @Date: 12:38 2018/8/20 */ public class IteratorTest { public static void main(String[] args) { List<String> list = new ArrayList<>(); list.add("a"); list.add("a"); list.add("a"); for (int i = list.size()-1; i >=0; i-- ) { if (list.get(i).equals("a")) { list.remove(i); if (list.isEmpty()) { break; } } } if (list.isEmpty()) { System.out.println("null"); } else { for (String str : list) { System.out.println(str); } } } }
2.利用迭代器遍历
package intership; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * @Author: yf.zuo * @Date: 12:38 2018/8/20 */ public class IteratorTest { public static void main(String[] args) { List<String> list = new ArrayList<>(); list.add("a"); list.add("a"); list.add("b"); Iterator iterator = list.iterator(); while (iterator.hasNext()){ if (iterator.next().equals("a")){ iterator.remove(); } } if (list.isEmpty()) { System.out.println("null"); } else { for (String str : list) { System.out.println(str); } } } }