• ArrayList 进阶方法之ListIterator


    同样看的都是jdk1.8 中 ArrayList中的源码,整理测试一下而已
    ListIterator(int index)方法,返回指定下标(包含该下标)后的值,此时index位置的元素就是新列表迭代器的第一个值。是不是感觉有点像substring(intindex)?
    注:ArrayList类同时还提供了 listIterator() 方法,此方法与listIterator(int index)的差异是index=0,
    此方法可以将ArrayList转换成ListIterator.
    下面是源码及测试代码

    源码:

     1     /**
     2      * Returns a list iterator over the elements in this list (in proper
     3      * sequence), starting at the specified position in the list.
     4      * The specified index indicates the first element that would be
     5      * returned by an initial call to {@link ListIterator#next next}.
     6      * An initial call to {@link ListIterator#previous previous} would
     7      * return the element with the specified index minus one.
     8      *
     9      * <p>The returned list iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
    10      *
    11      * @throws IndexOutOfBoundsException {@inheritDoc}
    12      */
    13     public ListIterator<E> listIterator(int index) {
    14         if (index < 0 || index > size)
    15             throw new IndexOutOfBoundsException("Index: "+index);
    16         return new ListItr(index);
    17     }

    测试代码:

     1 import java.util.ListIterator;
     2 
     3 public class listIteratorTest {
     4     public static void main(String[] args) {
     5         ArrayList<String> list = new ArrayList<String>();
     6         list.add("a");
     7         list.add("b");
     8         list.add("c");
     9         list.add("d");
    10         list.add("e");
    11         ListIterator<String> a = list.listIterator(2);
    12         while (a.hasNext()) {
    13             System.out.println(a.next());
    14         }
    15 
    16     }
    17 }
    18 
    19 运行结果:
    20 c
    21 d
    22 e
  • 相关阅读:
    Scrapy 使用 LinkExtractor 提取链接和使用 Exporter 导出数据
    Scrapy 使用 Item 封装数据、使用 Item Pipline处理数据
    XPath 和 CSS
    Scrapy 中的 Request 对象和 Respionse 对象
    Scrapy 框架结构及工作原理
    Scrapy 常用的shell执行命令
    mui html5 plus
    《C++ Primer》读书笔记—第二章 变量和基本类型
    eclipse+maven搭建ssm框架
    unique_ptr 智能指针(C++11)
  • 原文地址:https://www.cnblogs.com/yesiamhere/p/6601020.html
Copyright © 2020-2023  润新知