迭代器(iterator)有时又称游标(cursor)是程序设计的软件设计模式,可在容器(container,例如链表或阵列)上遍访的接口,设计人员无需关心容器的内容。html
1.Iterator是一个接口,它实现了如何使用迭代器,代码以下java
package java.util; public interface Iterator<E> { boolean hasNext(); E next(); void remove(); }
hasNext()
:遍历过程当中,断定是否还有下一个元素。(从Collection对象的第一个元素开始)设计模式
next()
: 遍历该元素。(即取出下一个元素)api
remove(): 移除刚刚遍历过的元素。数组
2.Iterable也是一个接口,它实现了返回一个迭代器,代码以下oracle
package java.lang; import java.util.Iterator; public interface Iterable<T> { Iterator<T> iterator(); }
Collection接口拓展了接口Iterable,根据以上的对Iterable接口的定义能够发现,其要求实现其的类都提供一个返回迭代器Iterator<T>对象的方法。spa
3.切记,对JAVA集合进行遍历删除时务必要用迭代器设计
package wm_collection; import java.util.*; public class test { public static void main(String[] args) { //使用了泛型 List<String> list=new ArrayList<String>(); list.add("e"); list.add("r"); int i; Iterator it= list.iterator(); //调用Iterator while(it.hasNext()){ String string=(String) it.next(); if(string.equals("e")) { it.remove(); } } Iterator i1= list.iterator(); while(i1.hasNext()){ System.out.println("a"); System.out.println(i1.next()); } /*for(i=0;i<list.size();i++){ System.out.println(list.get(i)); }*/ /*for(String str:list){ System.out.println(str); } }*/} }
由于在循环语句汇总删除集合中的某个元素,就要用迭代器iterator的remove()方法,由于它的remove()方法不只会删除元素,还会维护一个标志,用来记录目前是否是能够删除状态,如调用以前至少有一次next()方法的调用。code
4.for each与Iteratorhtm
for each是jdk5.0新增长的一个循环结构,能够用来处理集合中的每一个元素而不用考虑集合定下标。
格式以下
for(variable:collection){ statement; }
定义一个变量用于暂存集合中的每个元素,并执行相应的语句(块)。collection必须是一个数组或者是一个实现了lterable接口的类对象。