用for-each 边遍历ArrayList 边修改时:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
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进行遍历删除
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
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循环
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
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 (个人推荐,简洁快捷新特性)
1
2
3
4
5
6
7
8
9
10
11
|
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); } |
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://www.cnblogs.com/convict/p/13210740.html