12

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?

Ihor Patsian
  • 1,288
  • 2
  • 15
  • 25
AnkitSablok
  • 3,021
  • 7
  • 35
  • 52
  • You are not using iterator properly, it will added where the iterator is placed... in the first element if you don't never call `next()` – nachokk Sep 25 '13 at 02:07
  • How do I use it to insert the elements to the list? – AnkitSablok Sep 25 '13 at 02:08
  • 4
    Did you had a chance to read the [API....](http://docs.oracle.com/javase/7/docs/api/java/util/ListIterator.html#add%28E%29) – Jayamohan Sep 25 '13 at 02:08
  • `while(listIterator.hasNext()){ listIterator.next()... listIterator.add(..)`; – nachokk Sep 25 '13 at 02:09
  • @nachokk : so should I do something like for(int i = 0 ; i < 10 ; ++i){ while(listIterator.hasNext()){listIterator.next();listIterator.add(i);}} ? – AnkitSablok Sep 25 '13 at 02:12
  • you don't have to use `for(..)` just while – nachokk Sep 25 '13 at 02:13
  • What happens is contradictory to the explanations, as the last added element would be printed then. If it's true, though, it would be explaiable by that `add(...)` adds the element at the index the iterator is placed, but before the iterator, so the iterator afterwards points right after it. (Hope that makes sense to you...) Nevertheless, the output is expectable, since you iterate to the beginning, then call `println(next())` once, thus only printing the first element of the list. – Egor Hans Sep 02 '17 at 07:48

3 Answers3

20

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]

    }
 }
nachokk
  • 14,363
  • 4
  • 24
  • 53
  • I have a method like this "public void addToList(String[] strings){}" which accepts an array of strings and I want to add these strings to the list using listIterator – AnkitSablok Sep 25 '13 at 02:18
  • you don't have a `list` then.. you have an array.. if you still want to use `listIterator` you have to convert that array into a List with `Arrays.asList()` – nachokk Sep 25 '13 at 02:20
  • but the list I want to add elements to is a different list than the array, how do I do that? – AnkitSablok Sep 25 '13 at 02:22
  • @AnkitSablok then return `list.toArray()` – nachokk Sep 25 '13 at 02:24
  • @AnkitSablok Is there any good reason you need to use an iterator to do that ? Normally you would just use any of the answers here: https://stackoverflow.com/questions/12149314/adding-array-to-a-list-in-java – nos Jun 11 '17 at 22:26
0

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);
    }
  }
}
Egor Hans
  • 206
  • 1
  • 11
-1
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);
    }

}
jeff porter
  • 6,560
  • 13
  • 65
  • 123