Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List Iterator - Not working

Tags:

java

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?

like image 229
Jiya Jeya Avatar asked Aug 03 '26 23:08

Jiya Jeya


2 Answers

You're looking at the iterator itself.

use

iteratorNames.next()

to get the next item.

like image 151
tom Avatar answered Aug 06 '26 11:08

tom


Change the below line:

System.out.println(iteratorNames);

To:

System.out.println(iteratorNames.next());
like image 31
Gokul Nath KP Avatar answered Aug 06 '26 11:08

Gokul Nath KP