迭代器基础
一、迭代器的基本用法
1、terator的三个方法
next()获得序列的下一个元素
hasNext()判断序列是否还有下一个元素
remove()移除next最近返回的元素,必须在next()之后调用
实例:
import typeinfo.pets.*; import java.util.*; public class SimpleIterator { public static void main(String[] args) { // TODO Auto-generated method stub List<Pet> l = Pets.arrayList(7); Iterator<Pet> it = l.iterator(); System.out.println("[1]: " + l); System.out.print("[2]: "); for(Pet p : l) { System.out.print(l.indexOf(p) + ":" + p + " "); } System.out.println(); System.out.print("[3]: "); while(it.hasNext()) { System.out.print(it.next() + " "); } System.out.println(); it = l.iterator(); for(int i = 0; i < 4; i++) { it.next(); it.remove(); } System.out.println("[4]: " + l); } }
输出:
2、ListIterator
ListIterator只对List有效,可以前后遍历
方法:
- next()返回下一个元素,next指针后移,previous指针后移
- hasNext()列表中是否有未返回的元素
- nextIndex()返回next指针下标
- previous()返回前一个元素,previous指针前移,next指针前移
- hasPrevious()逆向遍历,是否还有没返回的元素
- previousIndex()返回previous指针下标
- remove()删除previous()或者next()最近返回的元素
- add()插入一个元素在next指针之前,previous指针之后
previous指针初始化时,就在next指针前面(即previous=-1 next = 0)
实例:
import java.util.*; import typeinfo.pets.*; public class ListIteration { public static void main(String[] args) { // TODO Auto-generated method stub List<Pet> l = Pets.arrayList(6); ListIterator<Pet> it = l.listIterator(); System.out.println("[1]: " + l); //正向遍历列表 System.out.print("[2]: "); while(it.hasNext()) { Pet p = it.next(); System.out.print("(" + p + ", " + it.previousIndex() + ", " + it.nextIndex() + ") "); } System.out.println(); //逆向遍历列表 System.out.print("[3]: "); while(it.hasPrevious()) { Pet p = it.previous(); System.out.print("(" + p + ", " + it.previousIndex() + ", " + it.nextIndex() + ") " ); } System.out.println(); //将2位置元素设置成r Rat r = new Rat(); for(int i = 0; i < 3; i++) { it.next(); } it.set(r); System.out.println("[4]: " + l); //删除后三个元素 it = l.listIterator(); while(it.hasNext()) { it.next(); } for(int i = 0; i < 3; i++) { it.previous(); it.remove(); } System.out.println("[5]: " + l); //在最后添加r it.add(r); System.out.println("[6]: " + l); } }
输出:
3、任何实现Iterable的类都可以使用foreach语法
import java.util.*; public class MyCollection implements Iterable<String>{ private String[] words; private int size ; MyCollection(String ...args) { words = args; for(String s : words) { if(s == null) break; size++; } } public Iterator<String> iterator() { return new Iterator<String>() { private int next = 0; public boolean hasNext() { return next < size; } public String next() { return words[next++]; } public void remove() { } }; } public static void main(String[] args) { // TODO Auto-generated method stub MyCollection m = new MyCollection("MyCollection","is","good"); for(String s : m) { System.out.print(s + " "); } } }
输出:
MyCollection is good