Iterator ite = Set.iterator();
Iterator ite = List.iterator();
ListIterator listite = List.listIterator();我们可以使用Iterator遍历Set、List或Map。但是ListIterator只能用于遍历List,它不能遍历Set。为什么?
我知道主要的区别在于使用迭代器我们只能在一个方向上运行,但是使用ListIterator我们可以在两个方向上运行。还有其他不同之处吗?与Iterator相比,ListIterator有何优势?
发布于 2012-06-11 18:06:42
区别在ListIterator的Javadoc中列出
你可以的
发布于 2013-07-30 13:49:28
有两点不同:
也就是说,我们可以通过使用Set和List来获得一个Iterator对象,如下所示:
通过使用Iterator,我们只能向前检索Collection对象中的元素。
迭代器中的方法:
1. `hasNext()`
2. `next()`
3. `remove()`迭代迭代器= Set.iterator();迭代器迭代器= List.iterator();
where as a ListIterator允许您在任一方向上遍历(向前和向后)。因此,除了迭代器之外,它还有两个方法,如hasPrevious()和previous()。此外,我们还可以获得下一个或前一个元素的索引(分别使用nextIndex()和previousIndex() )
ListIterator:中的方法
1. hasNext()
2. next()
3. previous()
4. hasPrevious()
5. remove()
6. nextIndex()
7. previousIndex()ListIterator listiterator =List.listIterator()
也就是说,我们不能从Set接口获取ListIterator对象。
参考资料:- What is the difference between Iterator and ListIterator ?
发布于 2013-12-11 18:30:09
迭代器是ListIterator的超类。
下面是它们之间的区别:
对于
iterator,您只能向前移动,但使用ListIterator,您还可以在读取元素时向后移动。ListIterator您可以在遍历时随时获取索引,而使用iterator时,这是不可能的。您只能检查下一个元素是否可用,但在listiterator中,您可以检查上一个和下一个代码< elements.iterator.listiterator可以在遍历时修改元素,这在iterator.中是不可能的
迭代器外观:
public interface Iterator<E> {
boolean hasNext();
E next();
void remove(); //optional-->use only once with next(),
dont use it when u use for:each
}ListIterator外观:
public interface ListIterator<E> extends Iterator<E> {
boolean hasNext();
E next();
boolean hasPrevious();
E previous();
int nextIndex();
int previousIndex();
void remove(); //optional
void set(E e); //optional
void add(E e); //optional
}https://stackoverflow.com/questions/10977992
复制相似问题