why ? when ? how ? what ?
Java 集合框架图
有了 Iterator 为什么还要有 ListIterator 呢?
Iterator 遍历的时候如果你想修改集合中的元素怎么办? ListIterator来了。
ListIterator有以下功能:
- 可以向两个方向(前、后)遍历 List
- 在遍历过程中可以修改 list的元素
- 将制定的元素插入列表中
ListIterator 有两种获取方式
- List.listIterator()
- List.listIterator(int location) //可以指定游标的所在位置
内部实现类源码如下:
private class ListItr extends Itr implements ListIterator{ ListItr(int index) { cursor = index; } public boolean hasPrevious() { return cursor != 0; } public E previous() { checkForComodification(); try { int i = cursor - 1; E previous = get(i); lastRet = cursor = i; return previous; } catch (IndexOutOfBoundsException e) { checkForComodification(); throw new NoSuchElementException(); } } public int nextIndex() { return cursor; } public int previousIndex() { return cursor-1; } public void set(E e) { if (lastRet < 0) throw new IllegalStateException(); checkForComodification(); try { AbstractList.this.set(lastRet, e); expectedModCount = modCount; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } public void add(E e) { checkForComodification(); try { int i = cursor; AbstractList.this.add(i, e); lastRet = -1; cursor = i + 1; expectedModCount = modCount; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } }}