A detailed analysis and discrimination of ListIterator and Iterator in JAVA
- 2020-07-21 08:15:29
- OfStack
When using the Java collection, you need to use Iterator. But there is also an iterator, ListIterator, in the java collection that you can use when using List, ArrayList, LinkedList, and Vector. What is the difference between these two iterators? Let's take a closer look. There is a point to be made that the iterator points to the position before the element.
Let's first look at what the methods of Iterator and ListIterator iterators are.
The Iterator iterator contains the following methods:
hasNext() : Returns true if the iterator points to an element after the location, otherwise returns false
next() : Returns the collection Iterator points to the element after the location
remove() : Deletes the element in the collection that Iterator points to after the location
The ListIterator iterator contains the following methods:
add(E e): Inserts the specified element into the list before the current position of the iterator
hasNext() : When traversing the list in a forward manner, returns true if there are elements after the list iterator, false if not
hasPrevious(): Returns true if the list iterator has elements in front of it, otherwise returns false
next() : Returns the ListIterator in the list pointing to the element after the location
nextIndex(): Returns the index of the element following the desired location of ListIterator in the list
previous(): Returns ListIterator in the list pointing to the element before the location
previousIndex() : Returns the index of the element before the desired location of ListIterator in the list
remove(): Removes the last element returned by next() or previous() from the list. When using the hasPrevious() method on an iterator, remove ListIterator pointing to the element before the position)
set(E e) : Changes the last element returned by next() or previous() from the list to the specified element e
1. The same
Both are iterators that can be used when traversing elements of a collection without interfering with its traversal process.
2. The difference between
1. Iterator can be applied to all collections, Set, List and Map, and subtypes of these collections. ListIterator, on the other hand, can only be used for List and its subtypes.
2.ListIterator has add methods and can add objects to List, while Iterator cannot.
3. Both ListIterator and Iterator have hasNext() and next() methods that enable sequential traversal, but ListIterator has hasPrevious() and previous() methods that enable reverse (sequential forward) traversal. Iterator is not possible.
4.ListIterator can locate the current index position and nextIndex() and previousIndex() can be implemented. Iterator does not have this feature.
5. Both can be deleted, but ListIterator can modify the object and set() can. Iterator is traversable only and cannot be modified.