解决ArrayList的java.util.ConcurrentModificationException

 
public class ListRemoveTest {   
	public static void main(String[] args) {   
	        ListRemoveTest test = new ListRemoveTest();   
	           
	        System.out.println("-1-使用jdk5.0以后的增强for循环去remove");   
	        List list = test.buildList();   
	        try {   
	            /*for (String str : list) {//会抛出异常 
	                list.remove(str);   
	            } */  
	        	for (int i = 0; i < list.size(); i++) {
					list.remove(list.get(i));//同样是remove(objec),这里不用增强for循环就不会出现异常
				}
	        } catch (Exception e) {   
	            e.printStackTrace();    
	        }   
	  
	        System.out.println("-2-使用Iterator的remove");   
	        list = test.buildList();   
	        try {   
	            Iterator iterator = list.iterator();   
	           while (iterator.hasNext()) { 
	        	    iterator.next();//要记得获取下一个
	                iterator.remove(); //移除当前对象
	            }   
	        } catch (Exception e) {   
	            e.printStackTrace();   
	        }   
	  
	        System.out.println("-3-iterator遍历+list的remove");   
	       try {   
	            list = test.buildList();   
	           for (Iterator iterator = list.iterator(); iterator.hasNext();) {   
	                String str = (String) iterator.next();   
	                //list.remove(str);//不能这样移 
	                iterator.remove();//应该这样移除
	            }   
	        } catch (Exception e) {   
	            e.printStackTrace();   
	        }   
	           
	        System.out.println("-4-使用list的remove(int)方法. [由后向前删除]");   
	        list = test.buildList();   
	        for (int i = list.size(); i > 0; i--) {   
	            list.remove(i - 1);   
	        }   
	  
	        System.out.println("-5-使用list的remove(int)方法. [由前向后删除]");   
	        list = test.buildList();   
	        for (int i = 0; i < list.size(); i++) {   
	            list.remove(0);   
	        }   
	    }   
	  
	    private List buildList() {   
	        List list = new ArrayList();   
	        list.add("a");   
	        list.add("b");   
	        list.add("c");   
	        return list;   
	    }   
	} 


运行结果:

-1-使用jdk5.0以后的增强for循环去remove
-2-使用Iterator的remove
-3-iterator遍历+list的remove
-4-使用list的remove(int)方法. [由后向前删除]
-5-使用list的remove(int)方法. [由前向后删除]


 

你可能感兴趣的:(java,iterator,list,exception,string,jdk,class)