Reputation: 159
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
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
Reputation: 370
al.iterator() does not return the first element of al.
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