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?
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]
}
}
I don't know why you want to insert elements to ArraList
by ListIterator
.
You can simply do this by ArrayList<String> list = new ArrayList<>(Arrays.asList(s));
But anyway you've already added all the elements of an Array
to ArrayList
with the approach you've mentioned. You just need to iterate through ArrayList
in Proper way like this :
import java.util.ArrayList;
import java.util.ListIterator;
public class ListIteratorTest {
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]);
}
//Iterate using ListIterator
while (listIterator.hasNext()) {
System.out.println((String) listIterator.next());
}
//Iterate by Enhanced For Loop
for (String val : list) {
System.out.println(val);
}
}
}
import java.util.ArrayList;
import java.util.ListIterator;
public class listTest {
public static void main(String[] args) {
ArrayList<String> al = new ArrayList<String>();
al.add("test");
al.add("ref");
ListIterator<String> ltr= al.listIterator();
while(ltr.hasNext())
{
int pos =ltr.nextIndex();
if (pos==1)
{
ltr.add("ted");
}
ltr.next();
}
System.out.println(al);
}
}