Dimitri Maziuk coughed up:
Thomas G. Marshall sez:
Read the fine API docs.
I do, quite a bit actually, and I spend even more time in the java source.
However it's fairly clear that I missed what you were saying, so lets just
chat this through quickly.
Index-based access in List is potentially O(n) (that's what
"sequential" means, you have to traverse the whole n nodes from the
start to get to n-th node) so use of iterator is preferred over
get()/set().
IOW, if you iterate over a java.util.List in a for( int i = 0; ... )
loop you may get O(n^2) time whereas the iterator will give you O(n).
Right.
Index-based access in an array/Vector is O(1), that's what makes it
"random access". Both iterator and for loop will give you O(n) time,
the only difference is that iterator is a new object that has some
extra cruft for iterating backwards and the lame concurrent
modification check for people who write multi-threaded programs while
knowing nothing about "synchronized". (See src.zip.)
It is still /useful/, which is counter to your statement that it is not.
The reason to use iterators is to keep the implementation details out of the
loop access. You want to uncouple the thing that needs to traverse the list
from the details of getting each cell from it. Using iterators allows you
to change the underlying object later. You know this. So it certainly
isn't the case that "all you're getting with iterator is a new object
instead of an int counter". I suppose that was what I was reacting to: the
devaluation of the iteration idiom.
You got it backwards: the problem is not accessing an array serially,
it's accessing a List randomly.
Yes. I think I misread your original point. You didn't answer this
specifically when I asked, but I can see now what you meant by
"sequential-access generic List". That generic list you talk about would be
like a linked list is: sequential only, unless provisions are made for
indexing.
You've never seen a
java.util.List mylist = OtherPeople'sCode.getSomeList();
for( int i = 0; i < mylist.size(); i++ )
mylist.get( i )...
Of /course/ I have. It's called bad design if the index is only used for
grabbing the data and nothing else. Iterators provide the perfect
abstraction for this: it allows you to have the underlying object manage the
access for you, allowing you to change it from a List to some other object.
And in 1.5 they give you an abbreviated way of indicating the exact same
iterator.