Well, if all you have is an Iterator, and you want to know how many items there are, the only way to do it is to go through each item. On the other hand, Iterators often come from Collections of some sort - if that's the case, and you want to know the size, use the size() method on the Collection, not the Iterator. Iterators aren't really designed for anything other than, well, iterating.
It's important to understand that the absence of a size() method in Iterator is not an accidental omission. It's very deliberate.
Some things that can be iterated don't know how many items there are. As a possibly-poor example, one could consider implementing an Iterator that returned lines typed at the console by the user, with some special keystroke being used to indicate end-of-data. Such an Iterator couldn't possibly know how many lines the user was going to type.
Other things that can be iterated can only find the number of items by a very expensive operation. A classic example is LinkedList. A LinkedList can be iterated very efficiently, but getting its size involves traversing the whole list.
Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.
I would think an iterator doesn't need to know how many things there are. that's not it's job. it is supposed to know how to get the next, maybe get the previous, is there another one, etc. it doesn't need knowledge of the size of what it's iterating over.
There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Joined: Jan 30, 2000
[Peter Chase]: A LinkedList can be iterated very efficiently, but getting its size involves traversing the whole list.
That's true for a typical linked list implementation, but not for a java.util.LinkedList. LinkedList maintains size as an instance field, and updates it whenever an element is added or removed. So getting the size at any moment is very easy. I think that most of the Java library collections work similarly. But the general point is valid - it's possible for some collections to have very slow or inefficient size() methods.