Java ArrayList Java ArrayList遍历修改代码实例解析
Convict 人气:0用for-each 边遍历ArrayList 边修改时:
public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); list.add("aa"); list.add("bb"); list.add("cc"); list.add("dd"); System.out.println(list); for (String s : list) { if (s.equals("dd")) { list.remove(s); } } System.out.println(list); }
会报错
可以改用如下方式:
① 用迭代器 iterator进行遍历删除
public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); list.add("aa"); list.add("bb"); list.add("cc"); list.add("dd"); System.out.println(list); Iterator<String> iterator = list.iterator(); while (iterator.hasNext()) { String next = iterator.next(); if (next.equals("dd")) { iterator.remove(); } } System.out.println(list); }
②:使用最原始的 for循环
public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); list.add("aa"); list.add("bb"); list.add("cc"); list.add("dd"); System.out.println(list); for (int i = 0; i < list.size(); i++) { String s = list.get(i); if (s.equals("dd")) { list.remove(s); } } System.out.println(list); }
③:采用jdk8 Collection中新增的方法removeIf (个人推荐,简洁快捷新特性)
public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); list.add("aa"); list.add("bb"); list.add("cc"); list.add("dd"); System.out.println(list); list.removeIf(next -> next.equals("dd")); System.out.println(list); }
加载全部内容