Scenario: Given a set, delete the element ‘b’ in the set, given two ways to delete it (front to back and back to front)

package com.study;
 
import java.util.ArrayList;
import java.util.List;
 
public class ListTest {
    public static void main(String[] args) {
        List<String> lists = new ArrayList<String>();
 
        lists.add("a 0");
        lists.add("a 1");
        lists.add("b 2");
        lists.add("b 3");
        lists.add("b 4");
        lists.add("c 5");
        lists.add("d 6");
        lists.add("d 7");
        lists.add("e 8");
 
        // Delete from front to back
        for(int i=0; i<lists.size(); i++){ System.out.println("begin i = "+ i + " list get("+i+") ="+lists.get(i));
            if(lists.get(i).substring(0.1).equals("b")){
                lists.remove(i);
 
            }
 
        }
        System.out.println("-- -- -- -- -- -- -- -- -- -- -- -- -- -- --");
        for(String s:lists)
            System.out.println(s);
 
        System.out.println("-- -- -- -- -- -- -- -- -- -- -- -- -- -- --");
 
        System.out.println();
 
        List<String> list1s = new ArrayList<String>();
 
        list1s.add("a 0");
        list1s.add("a 1");
        list1s.add("b 2");
        list1s.add("b 3");
        list1s.add("b 4");
        list1s.add("c 5");
        list1s.add("d 6");
        list1s.add("d 7");
        list1s.add("e 8");
 
        // The second way to delete is from back to front
        for(int i=list1s.size()-1; i>=0; i--){ System.out.println("begin i = "+ i + " list get("+i+") ="+list1s.get(i));
            if(list1s.get(i).substring(0.1).equals("b")){ list1s.remove(i); }}for(String s:list1s) System.out.println(s); }}Copy the code

The final result:

1. Move from front to back: when moving to “b 2”, the deletion condition is met, then “b 2” will be deleted, but the following elements will move forward, which will lead to the situation that the subscript does not correspond to the actual result, and the situation that the subscript does not correspond to the real coordinate will occur.

Results:

2. Move from back to front: Move from back to front When matching to meet the deletion conditions, the real coordinate of the element moves forward, the original position also moves forward, in the synchronous movement state, so there will not be missing deletion.

Link to this article: blog.csdn.net/qq_33883389…