动态删除ArrayList中的元素

  昨天一位项目组同事需要在ArrayList中删除所有不等于指定值的元素,但是她弄了很久,发现总是删得不完全。刚好我以前做过类似的功能,就告诉她是因为ArrayList删除元素后长度变小了,元素的索引也会跟着改变,但是迭代的下标没有跟着相应的改变的缘故。

  将一些删除方法做一些总结:

  

 1 /**
 2      * 删除Arraylist中值为"c"的元素
 3      */
 4     public static void main(String[] args) {
 5         
 6         List<String> list = new ArrayList<String>();
 7         
 8         //"c"在Arraylist不连续存储
 9         /*
10         list.add("c");
11         list.add("a");
12         list.add("c");
13         list.add("b");
14         list.add("c");
15         list.add("d");
16         list.add("c");
17         */
18         
19         //"c"在Arraylist有连续存储
20         list.add("a");
21         list.add("c");
22         list.add("c");
23         list.add("b");
24         list.add("c");
25         list.add("c");
26         list.add("d");
27         list.add("c");
28         
29         
30         //删除Arraylist中值为"c"的元素
31         
32         //有可能不能全部删除
33         //removeListElement1(list);
34         
35         //能够正确删除
36         //removeListElement2(list);
37         
38         //能够正确删除
39         //removeListElement3(list);
40     }
41     
42     
43     /**
44      *        删除list中值为"c"的元素
45      * 
46      *   这种方式:
47      *   
48      *   当值为"c"的元素在Arraylist中不连续存储的时候,是可以把值为"c"的元素全部删掉
49      *   
50      *   但是当值为"c"的元素在Arraylist中有连续存储的时候,就没有把值为"c"的元素全部删除
51      *   因为删除了元素,Arraylist的长度变小了,索引也会改变,但是迭代的下标没有跟着变小
52      */
53     public static void removeListElement1(List<String> list) {
54         for(int i=0;i<list.size();i++) {
55             if("c".equals(list.get(i))) {
56                 list.remove(i);
57             }
58         }
59         
60     }
61     
62     /**
63      * 删除Arraylist中值为"c"的元素
64      * 
65      * 这种方式:
66      * 
67      * 不管值为"c"的元素在Arraylist中是否连续,都可以把值为"c"的元素全部删除
68      */
69     public static void removeListElement2(List<String> list) {
70         for(int i=0;i<list.size();i++) {
71             if("c".equals(list.get(i))) {
72                 list.remove(i);
73                 --i;//删除了元素,迭代的下标也跟着改变
74             }
75         }
76     }
77     
78     /**
79      * 删除Arraylist中值为"c"的元素
80      * 
81      * 这种方式:
82      * 
83      * 不管值为"c"的元素在list中是否连续,都可以把值为"c"的元素全部删除
84      * 
85      * 需保证没有其他线程同时在修改
86      */
87     public static void removeListElement3(List<String> list) {
88         Iterator<String> iterator = list.iterator();
89         while(iterator.hasNext()) {
90             String str = iterator.next();
91             if("c".equals(str)) {
92                 iterator.remove();
93             }
94             
95         }
96     }

  

原文地址:https://www.cnblogs.com/luxh/p/2509314.html