zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    简单线程池的设计
    MFC开发--截图工具
    Win32小游戏--蜘蛛纸牌
    C++语言动态创建对象
    C++语言类之间的关系
    c++语言虚函数实现多态的原理(更新版)
    5-24 c++语言之【基础知识】
    小细节--关于printf的输出问题
    Win32小游戏--贪吃蛇
    2020北大夏令营 终末游记
  • 原文地址:https://www.cnblogs.com/yesiamhere/p/6601020.html
Copyright © 2011-2022 走看看