• 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

  • 相关阅读:
    chrome调试Android webview页面
    Ractive 的 一些认识
    backbone的一些认识
    关于Maven打包(Jar)时文件过滤的正确做法
    网页中实现微信登录(OAuth)的不完整记录
    将项目发布到Maven中央仓库时关于GPG的一些操作日志
    记录一下自己在 eclipse 中使用的 javadoc 模板
    记录一下MySQL的表分区常用操作
    在H5 App中实现自定义Token的注意事项
    再来复习一下Javascript中关于数组和对象的常用方法
  • 原文地址:https://www.cnblogs.com/westward/p/5503755.html
Copyright © 2020-2023  润新知