可以看到,Iterator删除了元素,并且把游标重新置为正确的位子。只要没有其他线程同时改变该集合,不会有任何问题。

  以下使自己写得一小段代码,分了三种情况进行说明:

    package com.iss; 
    import java.util.ArrayList; 
    import java.util.Iterator; 
    import java.util.List; 
    public class Test 
    { 
        /**
         * @param args
         */ 
        public static void main(String[] args) 
        { 
            // TODO Auto-generated method stub 
            List<String> list = new ArrayList(); 
             
            for(int i = 0; i<10; i++) 
            { 
                list.add("This is" + i); 
            } 
            System.out.println("hello"); 
             
            list.remove("This is1"); 
             
            for(Iterator iter = list.iterator(); iter.hasNext(); ) 
            { 
                String str = (String) iter.next(); 
                if(str.indexOf("1") != -1) 
                { 
                    //情况一 
                    iter.remove(); 
                    //情况二 
                    list.remove(str); 
                } 
            } 
             
            //情况三 
            for(String strs : list) 
            { 
                if(strs.indexOf("1") != -1) 
                { 
                    list.remove(strs); 
                    System.out.println(strs); 
                } 
            } 
             
            for(String strT : list) 
            { 
                System.out.println(strT); 
            } 
        } 
    }

package com.iss; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class Test {     /**      * @param args      */     public static void main(String[] args)     {         // TODO Auto-generated method stub         List<String> list = new ArrayList();                  for(int i = 0; i<10; i++)         {             list.add("This is" + i);         }         System.out.println("hello");                  list.remove("This is1");                  for(Iterator iter = list.iterator(); iter.hasNext(); )         {             String str = (String) iter.next();             if(str.indexOf("1") != -1)             {                 //情况一                 iter.remove();                 //情况二                 list.remove(str);             }         }                  //情况三         for(String strs : list)         {             if(strs.indexOf("1") != -1)             {                 list.remove(strs);                 System.out.println(strs);             }         }                  for(String strT : list)         {             System.out.println(strT);         }     } }

  这三种中只有一种有用,你可以试一试!