当我们创建一个集合以后,可以直接使用system.out.println()来打印这个集合,但是,我们需要可以对每个元素进行操作,所以,这里需要使用迭代器来遍历集合
迭代器其实就是集合取出元素的方式
调用List对象的iterator()方法,得到Iterator对象,这个类是个接口类型,因此可以知道返回的是Iterator接口的子对象
while()循环,条件是,List对象的hasNext()方法,返回布尔值不为false
循环里面调用List对象的next()方法,可以得到每一个元素
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List; public class IteratorDemo { /**
* @param args
*/
public static void main(String[] args) {
List<String> list=new ArrayList<String>();
list.add("taoshihan1");
list.add("taoshihan2");
list.add("taoshihan3");
Iterator iterator=list.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
}
} }
PHP版:
php中最常用的迭代式foreach(),我们也可以自己实现一个迭代器
<?php
$list=array("taoshihan1","taoshihan2","taoshihan3");
/**
* 迭代器
* @author taoshihan
*/
class MyIterator implements Iterator{
public $index=0;
public $arr;
public function __construct($arr){
$this->arr=$arr;
}
public function current(){
return $this->arr[$this->index];
}
public function next(){
++$this->index;
}
public function key(){
return $this->index;
}
public function valid(){
return isset($this->arr[$this->index]);
}
public function rewind(){
$this->index=0;
}
}
$myIterator=new MyIterator($list);
$myIterator->rewind();//指针指向第一个
while($myIterator->valid()){//循环 当元素为真时
echo $myIterator->current();//打印当前元素
$myIterator->next();//指针往后移动一个 }