迴圈刪除List陣列特定元素
阿新 • • 發佈:2022-03-28
一個數組,每次迴圈刪除符合條件的某些元素:
測試程式碼:
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 已刪除全部資料