ArrayList 進階方法之ListIterator

一樣看的都是jdk1.8 中 ArrayList中的源碼,整理測試一下而已
ListIterator(int index)方法,返回指定下標(包含該下標)後的值,此時index位置的元素就是新列表迭代器的第一個值。是否是感受有點像substring(intindex)?
注:ArrayList類同時還提供了 listIterator() 方法,此方法與listIterator(int index)的差別是index=0,
此方法能夠將ArrayList轉換成ListIterator.
下面是源碼及測試代碼java

源碼:測試

 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     }

測試代碼:this

 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
相關文章
相關標籤/搜索