I know that traversing LinkedList by indexing is bad, because list.get(n) is executed in linear time O(n). Thus i shouldn’t use indexing. I looked at the AbstactList.Itr that is returned by iterator() call, it uses get(cursor) too. I’m confused.
As pointed out by @axtavt , LinkedList.iterator() actually calls listIterator() which returns AbstactList.ListItr which extends AbstactList.Itr and it only adds implementations of ListIterator interface. Thus the machinery for getting next element is still the same as in AbstactList.Itr. `AbstactList.Itr‘s next(); calls get(n) on the specified list.
LinkedList inherits not only from
AbstractList, but also fromAbstractSequentialListwhich in turn implementsiterator()like this:and the
ListIteratorreturned byLinkedListis smart about using sequential access.So whether you use foreach,
iterator()orlistIterator(), you are always dealing with the same smart iterator type.