迭代器有两个功能:
- boolean hasNext():查看是否还有下一个元素
- E next():返回当前元素
先上代码
这是迭代器所用到的节点类:
public class MyListNode {
public String val;
public MyListNode prev;
public MyListNode next;
public MyListNode(String val){ this.val = val; }
}
迭代器类:
public class MyIterator {
public MyListNode cur;
public MyIterator(MyListNode head){
cur = head;
}
public boolean hasNext(){
return cur != null;
}
public String next(){
String val = cur.val;
cur = cur.next;
return val;
}
}
该迭代器需要一个指向当前对象的引用,并且在迭代器构建之初让该引用指向链表头结点。作为一个迭代器的使用者,cur指向的对象中的元素就是第一个未知元素,所以在每次提取元素的时候都会让cur = cur.next,这样就使用者就可以判断是否还有下一个元素( hasnext() )。因为这是一种面向对象的风格,所以在写迭代器方法的时候是站在使用者的角度考虑问题的。