[javaSE] 集合框架迭代器

当我们创建一个集合以后,可以直接使用system.out.println()来打印这个集合,但是,我们需要可以对每个元素进行操作,所以,这里需要使用迭代器来遍历集合

 

迭代器其实就是集合取出元素的方式

 

调用List对象的iterator()方法,得到Iterator对象,这个类是个接口类型,因此可以知道返回的是Iterator接口的子对象

while()循环,条件是,List对象的hasNext()方法,返回布尔值不为false

循环里面调用List对象的next()方法,可以得到每一个元素

 

import java.util.ArrayList;
 java.util.Iterator;
 java.util.List;


public class IteratorDemo {

    /**
     * @param args
     */
    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;
    $arrfunction __construct(){
        $this->arr=;
    }
    function current(){
        return $this->arr[$this->index];
    }
    next(){
        ++index;
    }
    keyfunction valid(){
        return isset(index]);
    }
    rewind(){
        $this->index=0;
    }
}
$myIterator=new MyIterator($list);
$myIterator->rewind();//指针指向第一个
while($myIterator->valid()){循环 当元素为真时
    echo current();打印当前元素
    next();指针往后移动一个

}    

 

相关文章

@ 注解能被用来为程序元素( 类、 方法、 成员变量等) 设置...
@ 1、线性表的概念 线性表是最常见也是最简单的一种数据结构...
简介 ArrayList是开发中使用比较多的集合,它不是线程安全的...
在 Java String类源码阅读笔记 里学习了String类的源码,Str...
话不多说,先上图。 1、基本概念 欲说线程,必先说进程。 进...
@ 网络基础 计算机网络是指两台或更多的计算机组成的网络,在...