4

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);
}


}
1
  • What do you expect your output to be ? Commented Nov 7, 2011 at 8:36

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

10 Comments

Thanks for you replay. i am unable to add new elements when i tried using iterator. as i specified, i was trying to add r in while loop. which is not working.
-1: You should at least quote the relevant part from the documentation.
It is working. The second print statement, which you have commented out, should include all four letters.
@BjörnPollex I disagree completely. The documentation is there to be read. The specification or the wording may change slightly, which would make the quotation obsolete. The point here is that the OP hasn't understood or more probably even read the Javadoc at all.
@jbrookover your comment is irrelevant to my answer. If you have an answer of your own I suggest you post it.
|
1

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);  
} 

1 Comment

Glad you got it sorted out after those three years! But this doesn't look like it'll terminate. Each time around the loop, you take one item off and add two?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.