Home  >  Article  >  Java  >  Different ways to use Iterator and ListIterator

Different ways to use Iterator and ListIterator

高洛峰
高洛峰Original
2016-12-13 17:35:441204browse

When we use List and Set, in order to traverse their data, we often use Iterator.
Using the drop generator, you don’t need to interfere with the traversal process. You only need to take out the data you want one at a time and process it. But there are differences when using it.
Both List and Set have iterator() to obtain their iterators. For List, you can also obtain its iterator through listIterator(). The two iterators are sometimes incompatible. The main differences between Iterator and ListIterator are in the following aspects:
1. ListIterator has an add() method, which can be Add objects to List, but Iterator cannot
2. ListIterator and Iterator both have hasNext() and next() methods, which can achieve sequential backward traversal, but ListIterator has hasPrevious() and previous() methods, which can achieve reverse (sequential traversal). before) traversal. Iterator cannot.
3. ListIterator can locate the current index position, and nextIndex() and previousIndex() can achieve this. Iterator does not have this functionality.
4. Both can delete objects, but ListIterator can modify objects, and the set() method can do so. Iierator can only be traversed and cannot be modified.

Because of these functions of ListIterator, operations on List data structures such as LinkedList can be implemented.
In fact, array objects can also be implemented using iterators.
org.apache.commons.collections.iterators.ArrayIterator can achieve this function, I have mentioned the usage before. For details, please refer to: In general, we can just use Iterator. If you need to retrieve records repeatedly, you can use ListIterator to expand your functionality (a bit like the rolling result set in JDBC).

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn