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