迭代器小结

为什么使用迭代器?

  • 数组的遍历,可以通过for循环来实现,其原因是数组对于数据的储存是有序的(order);但是,对于Set这种无序(no order)的数据结构,就无法通过for循环来实现,此时,我们就需要引入一种新的访问方式来实现对数据的操作——迭代器。
  • 迭代器是一种轻量级的对象操作,其接口有四个抽象方法:
 1 public interface Iterator<E> {
 2 
 3     boolean hasNext();
 4 
 5 
 6     E next();
 7 
 8 
 9     default void remove() {
10         throw new UnsupportedOperationException("remove");
11     }
12 
13 
14     default void forEachRemaining(Consumer<? super E> action) {
15         Objects.requireNonNull(action);
16         while (hasNext())
17             action.accept(next());
18     }
19 }

 

–Object next():返回集合里下一个元素。

–boolean hasNext():如果被迭代的集合还元素没有被遍历,则返回true。

–void remove() :删除集合里上一次next方法返回的元素

–void forEachRemaining(Consumer action),这是Java 8为Iterator新增的默认方法,该方法可使用Lambda表达式来遍历集合元素。

 

迭代器的内部简单实现:

 1 public class SimpleIter {
 2         private int size =elem.length;
 3         private int coursor=-1;      //由实现的方法可知,游标在开始遍历List的时候从下标【0】开始,所以初始值赋予-1
 4     
 5     public int size(){
 6         return this.size;
 7     }
 8     
 9     public boolean hasNext(){
10         return coursor+1<size;       //为了防止下标越界,所以coursor+1小于List长度
11     }
12 
13     public String next(){
14         coursor++;
15         return elem[coursor];
16     }
17     
18     public void remove(){
19         System.arraycopy(elem, coursor+1, elem, coursor,this.size-(coursor+1)); 
20         this.size--;
21         this.coursor--;              //为了使游标可以指向删除某元素之后的正确指向,每次删除元素,需要coursor-1
22     }    

 

posted @ 2017-03-23 16:33  NOthingAJ  阅读(189)  评论(0编辑  收藏  举报