所有的Collection接口的容器类都有一个Iteration方法,返回值是一个实现了Iteration接口的对象
Iteration的对象叫做迭代器,作用是对容器内的元素进行遍历操作
其实相当于一个指针,初始位置在第一个元素的左边
1.接口内的方法
Boolean hasNext(); 判断右边是否还有元素
object next(); 返回游标右边的元素,并且游标移动到下一个位置;因为下一个位置元素的类型不确定,返回值不确定
void remove(); 删除左边的元素,remove方法是迭代中唯一删除的安全的方法,删除时只能使用游标的remove方法,原容器的remove方法被锁死
2.遍历元素用法
注意要强制转化类型
import java.util.*;
public class NO6{
public static void main(String[] args){
Collection c = new HashSet();
c.add( new Name( "f1", "l1" ) );
c.add( new Name( "f2", "l2" ) );
c.add( new Name( "f3", "l3" ) );
Iterator i = c.iterator();//创建迭代器
while( i.hasNext() ){//当容器中还有元素时
Name n = (Name) i.next();//下一个的元素类型不确定,所以先强制转化
System.out.print( n.getFirstName() + " " );
}
}
}
3.删除的用法
注意只能使用迭代器的remove方法
import java.util.*;
public class NO6{
public static void main(String[] args){
Collection c = new HashSet();
c.add( new Name( "fff1", "lll1" ) );
c.add( new Name( "f2", "l2" ) );
c.add( new Name( "fff3", "lll3" ) );
for( Iterator i = c.iterator(); i.hasNext(); ) {
Name name = (Name) i.next();//都强制转化为Name类型
if( name.getFirstName().length() < 3) {
i.remove();//这里必须使用 i 的remove方法,必须使用迭代器的方法,因为原容器的方法被锁死
}
}
System.out.println(c);
}
}