ArrayList 进阶方法之ListIterator

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

源码:

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

测试代码:

 import java.util.ListIterator;

 public class listIteratorTest {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>();
list.add("a");
list.add("b");
list.add("c");
list.add("d");
list.add("e");
ListIterator<String> a = list.listIterator(2);
while (a.hasNext()) {
System.out.println(a.next());
} }
} 运行结果:
c
d
e
上一篇:算法学习之C语言基础


下一篇:Unity入门知识