1) Yes
2) Yes
3) No.
Also note that on LinkedLists using get(i)
is O(i) while getting the next element from an iterator (which is what for-each does) is O(1).
whether the sequence of elements picked from a list will always be the same
Yes. Quote from the API Javadoc:
An ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list.
2:
how it goes through list's elements, from 0 to size()-1
Yes.
3: No, you generally don't need to iterate through the list manually to get to an indexed element. The most used List implementation is ArrayList
, which is random access, i.e. you can access any of its elements directly, in constant time. For LinkedList
, list.get(i)
does iterate through the list till the desired element implicitly, as this implementation is not random-access.
According to the API doc contract of List.iterator():
Returns an iterator over the elements in this list in proper sequence.
So yes, iteration over the elements of a List
should happen from index 0 to size()-1. Theoretically, you could encounter an implementation that violates the contract, but then that's a bug in the implementation, not in your code.
for(Object o : list)
makes implicit use of the List
's Iterator
, returning elements in a deterministic order. for(int i = 0; i < list.size(); i++)
also selects items from the List
in a deterministic order, as by definition, List
s are ordered.
Also, look at java.util.ListIterator.
List<Object> list = new ArrayList<Object>();
for(ListIterator<Object> it = list.listIterator(); it.hasNext(); )
{
Object o = it.next();
it.nextIndex();
it.prevIndex(); // etc
}
@MichaelBorgwardt Such an implementation would be broken - it doesn't satisfy the contract for List.iterator.