Iterator之ListIterator简介

ListIterator是什么?

(参考自百度百科)

java中的ListIterator在Iterator基础上提供了add、set、previous等对列表的操作。但是ListIterator跟Iterator一样,仍是在原列表上进行操作。

Iterator源代码:

package java.util;
public interface Iterator<E> {    
boolean hasNext();   
E next(); 
void remove();
}

ListIterator源代码:

public interface ListIterator<E> extends Iterator<E> {
    boolean hasNext();
    E next();
    boolean hasPrevious();
    E previous();
    int nextIndex();
    int previousIndex();
    void remove();
    void set(E e);
    
    void add(E e);
}

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仅能遍历,不能修改。

自己写的测试code:

public class Temp1 {
    public static void main(String[] args) {
        String[] strings= "a b c d e f g h i j".split(" ");
        
        List<String> list= new ArrayList<>(Arrays.asList(strings)); 
        ListIterator<String> listIterator = list.listIterator();
        System.out.println(listIterator.next());
        System.out.println(listIterator.next());
        System.out.println(listIterator.next());
        listIterator.add("x");//abcxde...
        System.out.println(listIterator.previous());//x
        System.out.println(listIterator.previous());//b
        while (listIterator.hasNext()) {
            String string = (String) listIterator.next();
            System.out.println(string);
            
        }
        //abcxccxdefghij
        
        
        /*listIterator.remove();
        System.out.println(listIterator.next());
        listIterator.set("z");//zcde...
        System.out.println(listIterator.previous());*/
        
    }
}

output:
a
b
c
x
c
c
x
d
e
f
g
h
i
j

原文地址:https://www.cnblogs.com/westward/p/5503755.html