Points to note when deleting JAVA List

This article is reproduced from: https://www.cnblogs.com/zhangfei/p/4510584.html Author: zhangfei Please indicate the statement when reprinting.

When JAVA 's LIST is deleted, list.remove(o) is generally used; but this often causes problems. Let's first look at the following 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 returned result is:

1

2

3

This result is obviously not what we expected. We want to delete all elements of 2 in the List, but 2 appears in the output result. This is because when i is equal to 1, the element 2 with index 1 in the List is deleted. At this time, the list is [1, 2, 3], but next, after i increments, it is equal to 2. When list.get(i), the retrieved result becomes 3, that is to say, with the increase of the list element When deleting, the index changes accordingly. This is the trap. Therefore, we have to find an iterative way to delete the index without changing the index. After the iterator is created, it will establish a single chain pointing to the original object. The index table , when the original number of objects changes , the content of the index table will not change synchronously, that is, the cursor is used to maintain the index table, so it can be deleted like this:

 

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!

Some people may say that I deleted it in the iterator, why does the value of the list change? Think about this for yourself! If you can't figure it out, you can change careers!

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324138505&siteId=291194637