Notes for java when List is deleted

  • 2020-05-30 20:19:10
  • OfStack

LIST in java is normally used when deleted list.remove(o); But this often leads to problems. Here's the code:


package com.demo;
 
import java.util.ArrayList;
import java.util.List;
 
public class Test11 {
   
  public void delete(){
    List<Integer> list = new ArrayList<Integer>();
    list.add(1);
    list.add(2);
    list.add(2);
    list.add(3);
    for (int i = 0; i < list.size(); i++) {
      if(list.get(i)==2){
        list.remove(i);
      }
    }
    this.outputList(list);
  }
   
  private void outputList(List<Integer> list){
    for (Integer i : list) {
      System.out.println(i);
    }
  }
 
  public static void main(String[] args) {
    Test11 t = new Test11();
    t.delete();
     
  }
 
}

The return result is:


1

2

3

This result is obviously not our expectations, we hope to delete all of 2 List elements, but the output of 2, this is because the i is equal to 1, the deleted List index element 2 to 1, then list [1, 2, 3], but then, after increasing i, equal to 2, in list. get (i), and the result becomes 3, that is to say as list element deletion, index is changed, This is one of the trap, so we have to look for one when deleting index does not change iteratively to delete, and iterator was created to establish a single index table refer to the original object, while the number of the original object changes, the index table content don't change synchronization, cursor is used to maintain the index table, so it can be to delete:


package com.demo;
 
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
 
public class Test11 {
   
  public void delete(){
    List<Integer> list = new ArrayList<Integer>();
    list.add(1);
    list.add(2);
    list.add(2);
    list.add(3);
    this.iteratorDelete(list.iterator(), 2);
    this.outputList(list);
  }
   
  private void iteratorDelete(Iterator<Integer> it, int deleteObject){
    while(it.hasNext()){
      int i = it.next();
      if(i==deleteObject){
        it.remove();
      }
    }
  }
   
  private void outputList(List<Integer> list){
    for (Integer i : list) {
      System.out.println(i);
    }
  }
 
  public static void main(String[] args) {
    Test11 t = new Test11();
    t.delete();
     
  }
 
}

This code turns out to be correct!

One might say, I deleted it in iterator, why did the value of list change? Think it over for yourself! Thinking can't come out, can change a profession!

conclusion

The above is the whole content of this article, I hope the content of this article to your study or work can bring 1 definite help, if you have questions you can leave a message to communicate.


Related articles: