List特有的迭代器:listIterator
注意要想使用這個(gè)迭代器,集合最多向上轉(zhuǎn)型為L(zhǎng)ist引用,因?yàn)閏ollection引用中沒有此方法。
Iterator和ListIterator主要區(qū)別在以下方面:
- ListIterator有add()方法,可以向List中添加對(duì)象,而Iterator不能
- ListIterator和Iterator都有hasNext()和next()方法,可以實(shí)現(xiàn)順序向后遍歷,但是ListIterator有hasPrevious()和previous()方法,可以實(shí)現(xiàn)逆向(順序向前)遍歷。Iterator就不可以。
- ListIterator可以定位當(dāng)前的索引位置,nextIndex()和previousIndex()可以實(shí)現(xiàn)。Iterator沒有此功能。
- 都可實(shí)現(xiàn)刪除對(duì)象,但是ListIterator可以實(shí)現(xiàn)對(duì)象的修改,set()方法可以實(shí)現(xiàn)。Iierator僅能遍歷,不能修改。