Iterator迭代器使用
阿新 • • 發佈:2022-03-26
能使用Iterator迭代器的幾種資料結構型別:Collection中的List和Set均有迭代器,而Map資料結構沒有迭代器
使用Iterator實現遍歷和刪除
1 public static void IteratorTest1() 2 { 3 List<Integer> list = new ArrayList<>(); 4 list.add(5); 5 list.add(2); 6 list.add(1); 7 list.add(2); 8 Iterator<Integer> it = list.iterator();//獲得對應資料結構的迭代器 9 //使用迭代器進行遍歷陣列元素 10 while (it.hasNext()) 11 { 12 System.out.print(it.next() + " ");//next()函式不僅會獲得當前it位置的下一個元素值,還會把it向後移動一格 13 } 14 //使用迭代器刪除某一個元素:應考慮到每次獲取元素時都會使當前迭代器所在的位置後移一位,所以一定要注意控制迭代器的位置 15 while (it.hasNext()) 16 { 17 Integer num = it.next();//通過該方式使:此時it所在位置的值就是num 18 if (num == 2) //因為it即對應num,直接判斷後執行刪除即可 19 { 20 it.remove(); 21 } 22 } 23 }