想必很多经验不够丰富的java工程师在对数据集合进行删除操作时都会直接调用remove进行操作,然而这里面却存在一个巨大的陷阱,废话不多说,看下面的Demo:
1 /*************************************************************************
2 > File Name: DeleteListParams.java
3 > Author: Haming
4 > Created Time: 2017年07月28日 星期五 16时25分56秒
5 ************************************************************************/
6
7 import java.util.List;
8 import java.util.ArrayList;
9 import java.util.Iterator;
10
11 public class DeleteListParams{
12
13 public static void main(String[] args){
14 // ---------------------传统删除集合元素方式--------------------------------------------------
15 List<Integer> list = new ArrayList<Integer>();
16 list.add(1);
17 list.add(2);
18 list.add(2);
19 list.add(3);
20 System.out.println("list.hashCode = " + list.hashCode());
21
22 for(int i = 0; i < list.size(); i++){
23 System.out.println("list.get("+ i +") = " + list.get(i));
24 if(list.get(i) == 2){
25 list.remove(i);
26 System.out.println("after remove, list.hashCode = " + list.hashCode());
27 }
28 }
29
30 for(Integer integer : list){
31 System.out.println(integer);
32 }
33
34 //----------------------采用iterator方式删除集合元素--------------------------------------------
35 List<Integer> list2 = new ArrayList<Integer>();
36 list2.add(1);
37 list2.add(2);
38 list2.add(2);
39 list2.add(3);
40 System.out.println("list2.hashCode = " + list2.hashCode());
41
42 Iterator<Integer> it = list2.iterator();
43 for(int k = 0; k < list2.size(); k++){
44 while(it.hasNext()){
45 int ii = it.next();
46 if(2 == ii){
47 it.remove();
48 System.out.println("after remove, list2.hashCode = " + list2.hashCode());
49 }
50 }
51 }
52
53 for(Integer integ : list2){
54 System.out.println(integ);
55 }
56 }
57
58 }
输出结果是:
list.hashCode = 955299
list.get(0) = 1
list.get(1) = 2
after remove, list.hashCode = 30817
list.get(2) = 3
1
2
3
list2.hashCode = 955299
after remove, list2.hashCode = 30817
after remove, list2.hashCode = 995
1
3