list使用remove()方法删除元素

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
public class  {
public static void main(String[] args) {
String str1 = new String("abc");
String str2 = new String("abc");
String str3 = new String("abc");
String str4 = new String("abc");

List<String> list = new ArrayList<String>();
list.add(str1);
list.add(str2);
list.add(str3);
list.add(str4);


// 原因:List每remove掉一个元素以后,后面的元素都会向前移动,此时如果执行i=i+1,则刚刚移过来的元素没有被读取
System.out.println("list.size() = " + list.size());
for (int i = 0; i < list.size(); i++) {
String s = list.get(i);
if ("abc".equals(s)) {
list.remove(i);
}
}
System.out.println("after remove : list.size() = " + list.size());

// 使用foreach删除报错:Exception in thread "main" java.util.ConcurrentModificationException
for (String s : list) {
list.remove(s);
}

// 三种解决办法
// 1. 倒序遍历
System.out.println("list.size() = " + list.size());
for (int i = list.size() - 1; i >= 0; i--) {
String s = list.get(i);
if ("abc".equals(s)) {
list.remove(i);
}
}
System.out.println("after remove : list.size() = " + list.size());
// 2. 每移除一个元素以后把i移回来
System.out.println("list.size() = " + list.size());
for (int i = 0; i < list.size(); i++) {
String s = list.get(i);
if ("abc".equals(s)) {
list.remove(i);
i--;
}
}
System.out.println("after remove : list.size() = " + list.size());
// 3. 使用iterator.remove()方法移除
System.out.println("list.size() = " + list.size());
Iterator<String> it = list.iterator();
while (it.hasNext()) {
String s = it.next();
if ("abc".equals(s)) {
it.remove();
}
}
System.out.println("after remove : list.size() = " + list.size());
}
}