for循環刪除集合中的元素不正確

如下代碼指望輸出[1, 2, 6],實際輸出是[1, 2, 5, 6]。。。三種解決方法java

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Test {
    public static void main(String[] args) {
        List<Integer> intList = new ArrayList<Integer>();
        Collections.addAll(intList, 1, 2, 3, 5, 6);
        for (int i = 0; i < intList.size(); i++) {
            Integer value = intList.get(i);
            // 符合條件,刪除元素
            if (value == 3 || value == 5) {
                intList.remove(i);
            }
        }
        System.out.println(intList);
    }
}

1.使用Iteratorcode

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

public class Test {
    public static void main(String[] args) {
        List<Integer> intList = new ArrayList<Integer>();
        Collections.addAll(intList, 1, 2, 3, 5, 6);
        Iterator<Integer> it = intList.iterator();
        while (it.hasNext()) {
            Integer value = it.next();
            if (value == 3 || value == 5) {
                it.remove();
            }
        }
        System.out.println(intList);
    }
}

2.從最後一個元素開始遍歷索引

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Test {
    public static void main(String[] args) {
        List<Integer> intList = new ArrayList<Integer>();
        Collections.addAll(intList, 1, 2, 3, 5, 6);
        for (int i = intList.size() - 1; i >= 0; i--) {
            Integer value = intList.get(i);
            if (value == 3 || value == 5) {
                intList.remove(i);
            }
        }
        System.out.println(intList);
    }
}

3.維護索引,刪除一個元素後,索引-1rem

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Test {
    public static void main(String[] args) {
        List<Integer> intList = new ArrayList<Integer>();
        Collections.addAll(intList, 1, 2, 3, 5, 6);
        for (int i = 0; i < intList.size(); i++) {
            Integer value = intList.get(i);
            if (value == 3 || value == 5) {
                intList.remove(i);
                i--;
            }
        }
        System.out.println(intList);
    }
}
相關文章
相關標籤/搜索