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