Java迭代器 讲解

迭代器在其实就是指针,读取集合或者数组中的一个值,读完以后又指向下一条数据。

iterator()

迭代器只读,不能改效率要比for循环高

迭代器的一些方法:

HasNext()  如果仍有元素可以迭代,则返回 true

Next()返回迭代的下一个元素(取值)

remove()从迭代器指向的 collection 中移除迭代器返回的最后一个元素

用法

Set集合中无法用get查询,我们可以用迭代器

import java.util.*;

public class Set练习 {

    public static void main(String[] args) {
        Set<String> s=new HashSet<String>();            //创建一个Set集合
        s.add("你好");                    //插入
        s.add("早上好");
        s.add("我们一起玩吧");
        s.add("好啊");

   
        Iterator it=s.iterator();    //生成一个迭代器,并赋值给it
        while(it.hasNext()==true){          //while循环  迭代器的方法。如果仍有元素可以迭代则返回true  这里的==true可以省略
            Object obj=it.next();                //取出里面的对象,并赋值给obj
            System.out.println(obj);            //输出obj
        }
    }

}

在List集合中也可以使用

import java.util.*;

public class List练习 {

    public static void main(String[] args) {
       
        List<String> l=new ArrayList<String>();      //创建一个List集合
        l.add("你好");                                  //插入
        l.add("你叫什么名字");
        l.add("你多大了");
       
        Iterator it = l.iterator();                //建立一个迭代器,并赋值给it
        while (it.hasNext()) {                        //while循环,当所有的元素走完则停止
            Object obj=it.next();                    //将每次迭代中获取的元素赋值给obj并打印
            System.out.println(obj);
        }
       
    }
}

猜你喜欢

转载自www.linuxidc.com/Linux/2017-01/139182.htm