循环删除List数组特定元素
一个数组list,每次循环删除符合条件的某些元素:
测试代码:
public class ftext { public static void main(String[] args) throws Exception { cs (); } public static void cs () throws Exception { List<Integer> all = new ArrayList<Integer>(); all.add(1); all.add(2); all.add(3); all.add(4); all.add(5); all.add(6); all.add(7); all.add(8); all.add(9); all.add(10); int aa = 0; while (aa<60){ if(all.size() == 0){ System.out.println("已删除全部数据"); break; } List<Integer> xh = new ArrayList<Integer>(all); Iterator<Integer> iterator=xh.iterator();//实例化迭代器 while(iterator.hasNext()){ Integer str=iterator.next();//读取当前集合数据元素 if(str == aa){ all.remove(str); System.out.println("删除"+aa+"之后的list当中的数据为:"+all.size()); } } Thread.sleep(10); System.out.println("当前循环次数aa:"+aa); aa++; } } }
测试结果:
当前循环次数aa:0 删除1之后的list当中的数据为:9 当前循环次数aa:1 删除2之后的list当中的数据为:8 当前循环次数aa:2 删除3之后的list当中的数据为:7 当前循环次数aa:3 删除4之后的list当中的数据为:6 当前循环次数aa:4 删除5之后的list当中的数据为:5 当前循环次数aa:5 删除6之后的list当中的数据为:4 当前循环次数aa:6 删除7之后的list当中的数据为:3 当前循环次数aa:7 删除8之后的list当中的数据为:2 当前循环次数aa:8 删除9之后的list当中的数据为:1 当前循环次数aa:9 删除10之后的list当中的数据为:0 当前循环次数aa:10 已删除全部数据