List loop delete method

 

 If you want to delete some elements in the List cyclically, for example, delete elements whose value is 'a', if you use a normal for loop, you will easily miss deletion or report an error.

package com.pdnev;

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

import org.junit.Before;
import org.junit.Test;


public class RemoveList {
	List<String> list;
	
	// prepare data
	@Before
	public void setData(){
		list = new ArrayList<String>();
		list.add("a");list.add("b");list.add("c");list.add("a");list.add("b");list.add("b");list.add("d");list.add("c");list.add("c");list.add("d");list.add("c");
	}
	
	// test the correct method
	@Test
	public void removeElement(){
		System.out.println("Original data: "+ Arrays.asList(list));
		
		// delete from back to front
		for(int i = list.size()-1;i>=0;i--){
			if(list.get(i).equals("a"))	list.remove(i);
		}
		System.out.println("删除a后: "+ Arrays.asList(list));
		
		//Iterator delete
		Iterator<String> it = list.iterator();
		while(it.hasNext()){
			String s = it.next();
			if(s.equals("b")) it.remove(); //Cannot use list.remove
			
		}
		System.out.println("After deleting b: "+ Arrays.asList(list));
		
		// delete that will be missed
		for(int i = 0;i<list.size();i++){
			if(list.get(i).equals("c"))  list.remove(i);
		}
		System.out.println("After deleting c: "+ Arrays.asList(list));
		
		int size = list.size();
		for(int i = 0;i<size;i++){
			if(list.get(i).equals("d"))  list.remove(i);
		}
	}
}

 

Results of the:



It can be seen that there is no problem with the first use of deleting from back to front. The second method of deleting using Iterator is also fine.

But there is a problem with the output of deleting the line c, and there is still c. This is to delete using an ordinary for loop, which will be omitted. In addition, if the size is not obtained every time, an out-of-bounds exception will be reported.

 

If you use enhanced for. ConcurrentModificationException will be reported

 

(Because I am not familiar with junit, the code uses junit practice)

 

 

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326691467&siteId=291194637