CosmicCat
CosmicCat

Reputation: 612

Confused as to how .next() works in Java iterators without the use of a for-loop

I created a list of strings in Java and want to iterate through the elements (animal names) that I added using the iterator class. I was wondering why manually typing it.next() in the following code does not print out the animals one-by-one and just prints out the first animal "Dog".

    public static void main(String[] args) {
        LinkedList<String> animals = new LinkedList<>();

        animals.add("Dog");
        animals.add("Cat");
        animals.add("Fox");
        animals.add("Rabbit");

        Iterator<String> it = animals.iterator();
        String animal1 = it.next();

        System.out.println(animal1);
        it.next();
        System.out.println(animal1);
        it.next()
        System.out.println(animal1);

}

The output I get is:

Dog
Dog
Dog

Why does it not print all the animals line by line? like this:

Dog 
Cat
Fox
Rabbit

Upvotes: 1

Views: 41

Answers (1)

Robby Cornelissen
Robby Cornelissen

Reputation: 97150

Because you're only assigning the result of it.next() to animal1 for the first call.

This will give you the behavior you expect:

String animal1 = it.next();
System.out.println(animal1);

animal1 = it.next();
System.out.println(animal1);

animal1 = it.next()
System.out.println(animal1);

Upvotes: 2

Related Questions