List<T>的循环删除

场景:要删除List<T>中的元素

  List<T> tList;

  for(T t:tList){

       if(true){

         tempList.remove(t);

    }

     }

     运行时报错,因为在remove操作后tList已改变,for循环时拿不到索引值报错。

解决方法一

  List<T> tList;

  List<T> tempList = tList;

  for(T t:tList){

    if(true){

         tempList.remove(t);

    }

     }

  创建tempList存放tList,经验证此方法不可行,因tempList和tList指向同一个地址,拿不到索引值的错误同样存在,此方法不可行

解决方法二

  List<T> tList;

  List<T> tempList = new ArrayList<T>();

  for(T t:tList){

    if(false){

         tempList.add(t);

    }

     }

     经验证,此方法可行。

posted on 2013-11-23 10:19  jackvc  阅读(434)  评论(0编辑  收藏  举报

导航