1. 程式人生 > >Java編程:刪除 List 元素的三種正確方法

Java編程:刪除 List 元素的三種正確方法

key public 簡寫 字符 索引 什麽 exp his lan

刪除 List 中的元素會產生兩個問題:

  1. 刪除元素後 List 的元素數量會發生變化;
  2. 對 List 進行刪除操作可能會產生並發問題;

我們通過代碼示例演示正確的刪除邏輯

package com.ips.list;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

public class ArrayListRemove {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<String>();
        list.add("beijing");
        list.add("shanghai");
        list.add("shanghai");
        list.add("guangzhou");
        list.add("shenzhen");
        list.add("hangzhou");
        remove11(list, "shanghai");

    }

    private static void print(List<String> list){
        for (String item : list) {
            System.out.println("元素值:" + item);
        }
    }

    /*
     * 錯誤
     */
    public static void remove11(List<String> list, String target){
        int size = list.size();
        for(int i = 0; i < size; i++){
            String item = list.get(i);
            if(target.equals(item)){
                list.remove(item);
            }
        }
        print(list);
    }
    /*
     * 錯誤
     */
    public static void remove12(List<String> list, String target){
        for(int i = 0; i < list.size(); i++){
            String item = list.get(i);
            if(target.equals(item)){
                list.remove(item);
            }
        }
        print(list);
    }
    /*
     * 錯誤
     */
    public static void remove13(List<String> list, String target){
        int size = list.size();
        for(int i = size - 1; i >= 0; i--){
            String item = list.get(i);
            if(target.equals(item)){
                list.remove(item);
            }
        }
        print(list);
    }
    /*
     * 正確
     */
    public static void remove14(List<String> list, String target){
        for(int i = list.size() - 1; i >= 0; i--){
            String item = list.get(i);
            if(target.equals(item)){
                list.remove(item);
            }
        }
        print(list);
    }

    /*
     * 錯誤
     */
    public static void remove21(List<String> list, String target){
        for(String item : list){
            if(target.equals(item)){
                list.remove(item);
            }
        }
        print(list);
    }

    /*
     * 正確
     */
    public static void remove22(ArrayList<String> list, String target) {
        final CopyOnWriteArrayList<String> cowList = new CopyOnWriteArrayList<String>(list);
        for (String item : cowList) {
            if (item.equals(target)) {
                cowList.remove(item);
            }
        }
        print(cowList);
    }

    /*
     * 錯誤
     */
    public static void remove31(List<String> list, String target){
        Iterator<String> iter = list.iterator();
        while (iter.hasNext()) {
            String item = iter.next();
            if (item.equals(target)) {
                list.remove(item);
            }
        }
        print(list);
    }
    /*
     * 正確
     */
    public static void remove32(List<String> list, String target){
        Iterator<String> iter = list.iterator();
        while (iter.hasNext()) {
            String item = iter.next();
            if (item.equals(target)) {
                iter.remove();
            }
        }
        print(list);
    }

}
  • 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
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131

執行 remove11 方法,出現如下錯誤:

Exception in thread “main” java.lang.IndexOutOfBoundsException: Index: 5, Size: 5
at java.util.ArrayList.rangeCheck(ArrayList.java:635)
at java.util.ArrayList.get(ArrayList.java:411)
at com.ips.list.ArrayListRemove.remove11(ArrayListRemove.java:33)
at com.ips.list.ArrayListRemove.main(ArrayListRemove.java:17)

由於int size = list.size();提前獲取了 List 的大小,for 循環中刪除了兩個元素,導致出現數組越界問題。

執行 remove12 方法,出現如下錯誤:

元素值:beijing
元素值:shanghai
元素值:guangzhou
元素值:shenzhen
元素值:hangzhou

字符串“shanghai”沒有被刪除,該方法解決了數組越界問題,但沒有解決徹底刪除數據的問題,原因是這樣的,跟蹤 ArrayList.remove(Object 0) 方法:

    public boolean remove(Object o) {
        if (o == null) {
            for (int index = 0; index < size; index++)
                if (elementData[index] == null) {
                    fastRemove(index);
                    return true;
                }
        } else {
            for (int index = 0; index < size; index++)
                if (o.equals(elementData[index])) {
                    fastRemove(index);
                    return true;
                }
        }
        return false;
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

刪除元素時執行 else 邏輯,調用了 fastRemove(index) 方法:

    private void fastRemove(int index) {
        modCount++;
        int numMoved = size - index - 1;
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        elementData[--size] = null; // clear to let GC do its work
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

通過代碼我們發現:List 刪除元素的邏輯是將目標元素之後的元素往前移一個索引位置,最後一個元素置為 null,同時 size - 1;這也就解釋了為什麽第二個“shanghai”沒有被刪除。

執行 remove13 方法,正確:

元素值:beijing
元素值:guangzhou
元素值:shenzhen
元素值:hangzhou

執行 remove14 方法,正確:

元素值:beijing
元素值:guangzhou
元素值:shenzhen
元素值:hangzhou

那麽 remove13 與 remove14 有什麽區別呢?答案是沒有區別,但是 remove11 與 remove12 是有區別的,remove12 中每次for(int i = 0; i < list.size(); i++)執行都會計算 size 值,比較耗性能。

執行 remove21 方法,出現如下錯誤:

Exception in thread "main" java.util.ConcurrentModificationException
    at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:859)
    at java.util.ArrayList$Itr.next(ArrayList.java:831)
    at com.ips.list.ArrayListRemove.remove21(ArrayListRemove.java:82)
    at com.ips.list.ArrayListRemove.main(ArrayListRemove.java:17)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

產生java.util.ConcurrentModificationException異常。foreach 寫法實際上是對的 Iterable、hasNext、next方法的簡寫。因此我們從List.iterator()著手分析,跟蹤iterator()方法,該方法返回了 Itr 叠代器對象。

    public Iterator<E> iterator() {
        return new Itr();
    }
  • 1
  • 2
  • 3

Itr 類定義代碼:

    private class Itr implements Iterator<E> {
        int cursor;       // index of next element to return
        int lastRet = -1; // index of last element returned; -1 if no such
        int expectedModCount = modCount;

        public boolean hasNext() {
            return cursor != size;
        }

        @SuppressWarnings("unchecked")
        public E next() {
            checkForComodification();
            int i = cursor;
            if (i >= size)
                throw new NoSuchElementException();
            Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length)
                throw new ConcurrentModificationException();
            cursor = i + 1;
            return (E) elementData[lastRet = i];
        }

        public void remove() {
            if (lastRet < 0)
                throw new IllegalStateException();
            checkForComodification();

            try {
                ArrayList.this.remove(lastRet);
                cursor = lastRet;
                lastRet = -1;
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }

        final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
    }
  • 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

通過代碼我們發現 Itr 是 ArrayList 中定義的一個私有內部類,在 next、remove方法中都會調用 checkForComodification 方法,該方法的作用是判斷 modCount != expectedModCount是否相等,如果不相等則拋出ConcurrentModificationException異常。每次正常執行 remove 方法後,都會對執行expectedModCount = modCount賦值,保證兩個值相等,那麽問題基本上已經清晰了,在 foreach 循環中執行 list.remove(item);,對 list 對象的 modCount 值進行了修改,而 list 對象的叠代器的 expectedModCount 值未進行修改,因此拋出了ConcurrentModificationException異常。

執行 remove22 方法,正確:

元素值:beijing
元素值:guangzhou
元素值:shenzhen
元素值:hangzhou
通過 CopyOnWriteArrayList 解決了 List的並發問題。

執行 remove31 方法,出現如下錯誤:

Exception in thread “main” java.util.ConcurrentModificationException
at java.util.ArrayListItr.checkForComodification(ArrayList.java:859)atjava.util.ArrayListItr.checkForComodification(ArrayList.java:859)atjava.util.ArrayListItr.next(ArrayList.java:831)
at com.ips.list.ArrayListRemove.remove31(ArrayListRemove.java:109)
at com.ips.list.ArrayListRemove.main(ArrayListRemove.java:17)

與執行 remove21 產生的異常一致,問題產生的原因也一致。

執行 remove32 方法,正確:

元素值:beijing
元素值:guangzhou
元素值:shenzhen
元素值:hangzhou

Java編程:刪除 List 元素的三種正確方法