zoukankan      html  css  js  c++  java
  • java迭代器(Iterator)的理解

    java迭代器,一种模式,可以对一种数据在不清楚其具体内部结构(啥类型的数据)的情况下,可以依次遍历,取出其中的元素。

    方法:boolean hasNext():是否还有元素迭代。
    next():返回迭代的下一个元素。
    remove():从迭代器中移除上一次刚添加进来的元素。

    具体使用:
    List <String> s=new ArrayList<String>();
    s.add("hello");
    s.add("world");
    Iterator<String> it=s.iterator();
    while(it.hasNext()){ System.out.println(it.next());

    或者用for循环遍历取值:

    for(Iterator it  = s.iterator();it.hasNext();){
             String te= (String) it.next();}

    一些注意点:
    1.在用迭代器对集合进行操作时,不要进行集合的添加,集合的移除等,会产生异常,如:

    while(it.hasNext()){
                //s.remove(0);//Exception in thread "main" java.util.ConcurrentModificationException
    
                String te= (String) it.next();
    
                System.out.println(te);
            //  s.add("test wrong");//在操作迭代器的同时,操作list集合。Exception in thread "main" java.util.ConcurrentModificationException
    
            }

    2.remove的深刻理解:
    iterator的remove()方法的前边必须要有next()方法,先获得下一个,remove,是将刚才next()读出的在集合中的给remove掉。可进行一个测试:

    public class Putexercise {
        public static void main(String[] args) {
            List <String> s=new ArrayList<String>();
            s.add("hello");
            s.add("world");
            Iterator it=s.iterator();
            int flag=0;
            while(it.hasNext()){
    
    
                String te= (String) it.next();
                if(flag==0){
                    it.remove();
                    flag=1;
                }
    
            }
    
            System.out.println(s.get(0));
            System.out.println(s.get(1));//此时只能输出world,报异常,list的长度为1.
        }
    }
    

    Iterator和ListIterator主要区别在以下方面:
    1. ListIterator有add()方法,可以向List中添加对象,而Iterator不能
    2. ListIterator和Iterator都有hasNext()和next()方法,可以实现顺序向后遍历,但是ListIterator有hasPrevious()和previous()方法,可以实现逆向(顺序向前)遍历。Iterator就不可以。
    3. ListIterator可以定位当前的索引位置,nextIndex()和previousIndex()可以实现。Iterator没有此功能。
    4. 都可实现删除对象,但是ListIterator可以实现对象的修改,set()方法可以实现。Iierator仅能遍历,不能修改。

  • 相关阅读:
    n个元素进栈,有几种出栈方式
    The following IP can be used to access Google website
    一个未排序整数数组,有正负数,重新排列使负数排在正数前面,并且要求不改变原来的 相对顺序 比如: input: 1,7,-5,9,-12,15 ans: -5,-12,1,7,9,15 要求时间复杂度O(N),空间O(1) 。
    当今世界最受人们重视的十大经典算法
    指针
    变量作用域和生存期
    一篇文章搞清spark内存管理
    Spark的Shuffle是怎么回事
    一篇文章搞清spark任务如何执行
    scala这写的都是啥?一篇文章搞清柯里化
  • 原文地址:https://www.cnblogs.com/wangxiaopei/p/8551239.html
Copyright © 2011-2022 走看看