I want to be able to insert elements to the ArrayList<String>
using ListIterator
, but somehow I am confused even after reading the documentation related to the add method of the ListIterator
class, if I do something like this
for(int i = 0 ; i < list.size() ; ++i)
listIterator.add( list.get(i) );
What does this code snippet do to my list iterator, where does it move the list iterator?
When I run the following code I get the result as "Hi" -:
import java.util.ArrayList;
import java.util.ListIterator;
public class ListIter {
public static void main(String[] args) {
String[] s = {"Hi", "I", "am", "Ankit"};
ArrayList<String> list = new ArrayList<>();
ListIterator<String> listIterator = list.listIterator();
for (int i = 0; i < s.length; ++i) {
listIterator.add(s[i]);
}
while (listIterator.hasPrevious()) {
listIterator.previous();
}
System.out.println(listIterator.next());
}
}
Kindly tell how is this output being generated?
Iterator is for iterating, not adding objects. List on the other hand is iterable (therefore it has Iterator ) but also it is able to manage entities, therefore the add .
The add() method of ListIterator interface is used to insert the given element into the specified list. The element is inserted automatically before the next element may return by next() method.
ListIterator is one of the four java cursors. It is a java iterator that is used to traverse all types of lists including ArrayList, Vector, LinkedList, Stack, etc. It is available since Java 1.2. It extends the iterator interface.
Obtain an iterator to the start of the collection by calling the collection's iterator( ) method. Set up a loop that makes a call to hasNext( ). Have the loop iterate as long as hasNext( ) returns true. Within the loop, obtain each element by calling next( ).
You are not using iterator properly. The correct way using iterators is traverse the list with the iterator itself rather than by index.
ListIterator<SomeObject> listIterator = list.listIterator();
while(listIterator.hasNext()){
SomeObject o = listIterator.next();
listIterator.add(new SomeObject());
}
Read the ListIterator#add()
A simple example:
public static void main(String args []){
List<String> list= new ArrayList<String>();
list.add("hi");
list.add("whats up");
list.add("how are you");
list.add("bye");
ListIterator<String> iterator = list.listIterator();
int i=0;
while(iterator.hasNext()){
iterator.next();
iterator.add(Integer.toString(i++));
}
System.out.println(list);
//output: [hi, 0, whats up, 1, how are you, 2, bye, 3]
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With