Java 循环删除list中指定元素
1.for循环遍历删除指定元素
List<String> list = new ArrayList<>(Arrays.asList("a","b","c","f","b","e","d")); for (int i = 0; i < list.size(); i++) { System.out.println("i="+i+"//str="+list.get(i)); if (list.get(i).equals("b")) { list.remove(i); } }
程序运行结果如图:
由结果分析可知,利用for遍历删除,删除某个元素之后,list的大小发生变化,索引也发生变化,当删除索引为1的b之后,继续根据索引访问索引为2的元素,由于删除的缘故后面元素自动往前移动一位,故此时索引2上的元素已经不再是c,而变成了f,也就是如图所打印出来的结果,故for循环适合删除特定一位元素,不适合循环删除特定元素;
2.增强for循环删除指定元素
List<String> list = new ArrayList<>(Arrays.asList("a","b","c","f","b","e","d")); for (String s : list) { System.out.println("------"+s+"------"); if ("b".equals(s)) { list.remove(s); } }
程序运行结果如图:
3.iterator删除指定元素
List<String> list = new ArrayList<>(Arrays.asList("a","b","c","f","b","e","d")); Iterator<String> iterator = list.iterator(); while (iterator.hasNext()) { String next = iterator.next(); System.out.println("------"+next+"------"); if ("b".equals(next)) { iterator.remove(); } } System.out.println(list.toString());
结果如图:
可以正常删除