JAVA 의 집합 과 교체 기 요소 삭제

5844 단어 제로 베이스
JAVA 의 집합 과 교체 기 요소 삭제
  • 집합 구조 가 바 뀌 면 교체 기 를 다시 가 져 와 야 합 니 다. 그렇지 않 으 면 이상 이 발생 할 수 있 습 니 다: java. util. Concurrent ModificationException
  • 반복 집합 과정 에서 집합 대상 의 reove 방법 으로 요 소 를 삭제 할 수 없습니다. 즉, collection. reove () 를 사용 합 니 다.이상 발생: java. util. ConcurrentModificationException
  • 교체 기 를 사용 할 때 교체 기의 reove 방법, 즉 iterator. reove () 를 사용 해 야 합 니 다.원 소 를 삭제 합 니 다
  • import java.util.ArrayList;
    import java.util.Collection;
    import java.util.Iterator;
    
    /*
          :                           
             :          ,         
    
          :         ,         remove       ,
             c.remove();     :java.util.ConcurrentModificationException
                 ,       remove  , it2.remove();     
    */
    
    public class CollectionTest05 {
        public static void main(String[] args) {
            Collection c = new ArrayList();
            /*
              :                           
                 :          ,         
            */
            Iterator it = c.iterator();
    
            //       ,            ,
            //  next        :
            //java.util.ConcurrentModificationException
    
            c.add("abcd");
            c.add(100);
    
            Iterator it2 = c.iterator();
            //    
            while(it2.hasNext()){
                Object o = it2.next();
                //    
    
    //            c.remove();
                /*
                     remove       ,         ,          ,
                      java.util.ConcurrentModificationException
                 */
    
                //      remove         
                it2.remove();    //                
                /*        。。      :
                                 ,           
                   remove                 ,
                         ,               ,       。
    
                     remove                 ,          。
                 */
                System.out.println(o);
            }
            System.out.println(c.size());  //0
        }
    }
    

    좋은 웹페이지 즐겨찾기