ListIterator与Iterator迭代关系

直接上代码:
ListIterator是List集合中特有的迭代器,但是没有什么太大的用处,原因是,使用ListIterator迭代元素,必须使用while(lt.hasNext()){System.out.println(lt.next()); }迭代后再使用ListIterator。ListIterator是倒序迭代,所以在遍历集合元素时一般不会使用。
但是也有它的作用:
发生ConcurrentModificationException异常时,可以避免此异常发生。具体请看ConcurrentModificationException文章概述。

package list.arraylist;

import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;

/*
 * ListIterator listIterator():List集合特有迭代器
 * boolean hasPrevious():判断集合中是否含有元素,相当于hasNext();
 * E previous():获取元素,并将指针指向下一个元素,相当于next();
 */
public class ListIteratorDome {
    public static void main(String[] args) {
    List<String> st = new ArrayList<String>();
    st.add("hello");
    st.add("world");
    st.add("java");
  /*  //Iterator  这样子写hasPrevious()与previous()迭代不出来
    Iterator it = st.iterator();
    while(it.hasNext()){
        System.out.println(it.next());
    }*/
  //Listc listIterator():List集合特有迭代器
    ListIterator lt = st.listIterator();
    while(lt.hasNext()){
        System.out.println(lt.next());
    }
  //boolean hasPrevious():判断集合中是否含有元素,相当于hasNext();?
    System.out.println("相反方向遍历");
    while(lt.hasPrevious()){
   //E previous():获取元素,并将指针指向下一个元素,相当于next();
        System.out.println(lt.previous());
    }
    //System.out.println(st);
    }
}

猜你喜欢

转载自blog.csdn.net/My_CODEart/article/details/80425624