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<E> {
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();
}
}
}