Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding elements to ArrayList while using Iterator in Java

I had a problem with adding elements to my ArrayList while using an Iterator. In the following code it gives me this output:

a
k
s

But still it misses the one I had added through iterator. i.e I am missing r in my output. Is there a way I can add elements to an ArrayList using an Iterator?

import java.util.ArrayList;
import java.util.ListIterator;
public class Test 
{
public static void main(String args[])
{
    ArrayList<String> array_test= new ArrayList<String>();
    array_test.add("a");
    array_test.add("k");
    array_test.add("d");
    array_test.add("s");
    array_test.remove("d");
    ListIterator<String> it=array_test.listIterator();
    while(it.hasNext())
    {   
        String link=it.next();  
        it.add("r");
        System.out.println(link);

    }   
    //System.out.println("Contents of arrays list "+array_test);
}


}
like image 602
prashanth Avatar asked Oct 15 '25 21:10

prashanth


2 Answers

Check the Javadoc. It is working as documented. Adding an element during an iteration doesn't return that element via the iterator unless you go backwards.

like image 166
user207421 Avatar answered Oct 18 '25 14:10

user207421


Sorry for my late reply. Here is how i resolved this issue.

for(ListIterator it=array_test.listIterator();it.hasNext();){ 
 String link=it.next(); 
   it.add("r");
   it.previous();
   it.add("kk");
   it.previous();
System.out.println(link);  
} 
like image 29
prashanth Avatar answered Oct 18 '25 12:10

prashanth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!