1. 程式人生 > >arraylist 為什麼 刪除元素時要使用迭代器而不能使用遍歷

arraylist 為什麼 刪除元素時要使用迭代器而不能使用遍歷

因為你要是遍歷了,arraylist 的長度就變了,容易陣列越界和下標問題

 

public class Test {

     public  static  void  main(String[] args)  {          ArrayList<Integer> list =  new  ArrayList<Integer>();
         list.add( 2 );          Iterator<Integer> iterator = list.iterator();          while (iterator.hasNext()){             
Integer integer = iterator.next();              if (integer== 2 )                  iterator.remove();    //注意這個地方         
}      } }