I've below code:
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
public class IteratorExample {
public static void main(String[] args) {
List<String> listnames = new ArrayList<String>();
listnames.add("Tom");
listnames.add("Finn");
listnames.add("Harry");
ListIterator<String> iteratorNames = listnames.listIterator();
while (iteratorNames.hasNext()) {
System.out.println(iteratorNames);
}
}
}
When I execute, I am getting strange output like below(which differs everytime when I run the program):
java.util.ArrayList$ListItr@a200d0c
java.util.ArrayList$ListItr@a200d0c
java.util.ArrayList$ListItr@a200d0c
java.util.ArrayList$ListItr@a200d0c
java.util.ArrayList$ListItr@a200d0c
Also the program is running infinitely.
Why it is not printing the list values?
You're looking at the iterator itself.
use
iteratorNames.next()
to get the next item.
Change the below line:
System.out.println(iteratorNames);
To:
System.out.println(iteratorNames.next());
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