Nicola Amadio
Nicola Amadio

Reputation: 159

Why does this java iterator loop print also the first element?

import java.util.*;
public class IteratorDemo {

   public static void main(String args[]) {
      // Create an array list
      ArrayList al = new ArrayList();

      // add elements to the array list
      al.add("C");
      al.add("A");
      al.add("E");
      al.add("B");
      al.add("D");
      al.add("F");

      // Use iterator to display contents of al
      System.out.print("Original contents of al: ");
      Iterator itr = al.iterator();

      while(itr.hasNext()) {
         Object element = itr.next();
         System.out.print(element + " ");
      }
      System.out.println();
    }
  }

I don't get it. If al.iterator() returns the first element of al, why if I put itr.next()(which should be the second I'm guessing) in element and then print element does it print the first element and not the second?

I'm new to java. Making a parallel with c/c++, is Iterator like a pointer and Iterator.next() like the dereferenced pointer? Can someone explain to me what's actually happening at a low level when I do what's in the code?

Upvotes: 0

Views: 2704

Answers (3)

Ousmane D.
Ousmane D.

Reputation: 56433

Calling the iterator() returns an iterator over the elements in the list, not the first element. in fact if this returned the first element, then the condition while(itr.hasNext()) wouldnt make any sense.

It's only when you call next() that the next element in the iteration is returned.

So, if you want to exclude the first element then you'll need to do:

 if(itr.hasNext()) itr.next();

before the loop.

Also, as an aside I'd recommend you use parameterized types rather than raw types i.e. your ArrayList should be declared ArrayList<String> al = new ArrayList<>(); and your iterator as Iterator<String> itr = al.iterator();.

Given that all you want to do in this case is to print the element to the console there is no need to use an Iterator at all as it's simpler to do:

 al.forEach(element -> System.out.print(element + " "));

Upvotes: 2

M.Soyturk
M.Soyturk

Reputation: 370

al.iterator() does not return the first element of al.

enter image description here

You can imagine the iterator like in this picture. The method iterator() provides an iterator so that you can iterate through the elements of list. It doesn't give the first element when you call it. Every time you call next() method it grabs you the next element. That's why when you call next() for the first time it gives you the first element.

Upvotes: 2

Thiyagu
Thiyagu

Reputation: 17890

al.iterator() (javadoc) returns an Iterator to the collection (your ArrayList in this case) and not the first element. You then you use the iterator iterate over the elements of the collection (using hasNext and next)

Upvotes: 0

Related Questions