Iterator迭代器使用

能使用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     }

 

posted @ 2022-03-26 19:05  jue1e0  阅读(24)  评论(0)    收藏  举报