Reputation: 612
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
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